PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 19, 2022

[FIXED] get correct data from array

 January 19, 2022     laravel-5, php     No comments   

Issue

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();

Solution

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



Answered By - Sumit Wadhwa
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing