The Codesee The Codesee - 3 months ago 6
JSON Question

Select from JSON with certain conditions

If I had the JSON below, how would I get the value of

Name
and
Age
when
ID == 6
?

[{"Name":" Jim", "ID":"6", "Age": "0"},{"Name":" Bob", "ID":"53", "Age": "0"}]


I have attempted to do this so far but I get the following error:


Notice: Trying to get property of non-object on line 3


$json = '[{"Name":" Jim", "ID":"6", "Age": "0"},{"Name":" Bob", "ID":"53", "Age": "0"}]';
$json2 = json_decode($json);
if($json2->ID == '6') {
echo $json2->Name;
echo $json2->Age;
}

Answer

With a simple loop:

$json = '[{"Name":" Jim", "ID":"6", "Age": "0"},{"Name":" Bob", "ID":"53", "Age": "0"}]';
$array = json_decode($json);
foreach($array as $person){
   if($person->ID == '6') {
       echo $person->Name;
       echo $person->Age;
   }
}

If you have to access more than one person in the array, it might make sense to create a new array indexed on the id:

$json = '[{"Name":" Jim", "ID":"6", "Age": "0"},{"Name":" Bob", "ID":"53", "Age": "0"}]';
$array = json_decode($json);
$indexPeopleArray=[];
foreach($array as $person){
   $indexPeopleArray[$person->ID]=$person;
}

Then you can access each person simply:

echo $indexPeopleArray[6]->name; //jim
echo $indexPeopleArray[53]->name; //bob
Comments