Skip to content
Advertisement

get correct data from array

i am trying to decode array. this is my array

array:4 [▼
  "_token" => "tgPAddbrf3hI5tBIQIGyFYe9Y5RpwCj3rpZG5uVf"
  "resident_id" => array:4 [▼
    117 => "117"
    114 => "114"
    116 => "116"
    118 => "118"
  ]
  "available" => array:1 [▼
    116 => "2020-09-22"
  ]
  "out_of_community" => array:1 [▼
    118 => "2020-09-22"
  ]
]

i am using foeach to get answer like

resident_id  available    out_of_community
116         "2020-09-22"  null
118           null        "2020-09-22"

is it possible from foreach. my code for it

and when i save it will shown “Call to a member function save() on array”

 foreach ( $arr['resident_id'] as $resident_id ) {
             $newArr[] = [
                'resident_id' => $resident_id,
                'present_in_community' => isset($arr['present_in_community'][$resident_id]) ? $arr['present_in_community'][$resident_id] : null,
                'out_of_community' => isset($arr['out_of_community'][$resident_id]) ? $arr['out_of_community'][$resident_id] : null,
             ]; 
            
             
             
        }
        
        $resident = new ResidentStatus;

            $resident->resident_id= $newArr['resident_id'];
            $resident->present_in_community = $newArr['present_in_community'];
            $resident->out_of_community = $newArr['out_of_community'];
            $resident->save();

Advertisement

Answer

Is this what you’re looking for:

$arr = .... // this is the array you mentioned above

$newArr = [];

foreach ( $arr['resident_id'] as $resident_id ) {
     $newArr[] = [
        'resident_id' => $resident_id,
        'available' => isset($arr['available'][$resident_id]) ? $arr['available'][$resident_id] : null,
        'out_of_community' => isset($arr['out_of_community'][$resident_id]) ? $arr['out_of_community'][$resident_id] : null,
     ]; 
}

// finally save all entries in the db
ResidentStatus::insert( $newArr );

Note: make sure available and out_of_community columns are nullable by default in the db

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement