Reputation: 3781
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;
}
Upvotes: 1
Views: 40
Reputation: 1290
You can get it by using
if($json2[0]->ID == '6') {
echo $json2[0]->Name;
echo $json2[0]->Age;
}
//because in json [
indicates the array. so when you decode it from using json_decode
the array created like.
array[0][Name]
array[0][Age]
array[0][Age]
array[1][Name]
array[1][Age]
array[1][Age]
The answer of @steve is also the right.
Upvotes: 1
Reputation: 20469
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
Upvotes: 2