Hi I have a Json format like below:
{
"result":0,
"status":[
{
"id":"00001",
"vid":"yes"
},
{
"id":"00002",
"vid":"yes"
},
{
"id":"00003",
"vid":"no"
}
]
}
I want to use the json_decode
function in PHP to decode the id
values such as below:
00001
00002
00003
here is the code I am using:
$url = file_get_contents("URL");
foreach(json_decode($url, true) as $key=>$value){
foreach($value->status[0] as $key1=>$value1){
echo $value1->id;
}
}
The problem seems to be with status[0]
as far as I know using status[0]
is the only way to select the status
key. However I can't get the loop to work correctly.
I get the error: Trying to get property of non-object
meaning status[0]
is not finding status
in the Json array however I have no idea why this is since it works when I pull a value like:$id = $url->status[0]->id;
If anyone has any suggestions or advice I'd greatly appreciate it. Thanks
I removed some commas from your json data.
Code: demo: https://3v4l.org/C1Mda
$json = '{"result":0,"status":[{"id":"00001"},{"id":"00002"},{"id":"00003"}]}';
foreach(json_decode($json, true)['status'] as $status){
echo $status['id'] , "
";
}
Output:
00001
00002
00003
Because you are using json_decode's true
parameter, an array is generated. You need to use square bracket syntax.
Or you can use objects:
foreach(json_decode($json)->status as $status){
echo $status->id , "
";
}
Your JSON is invalid look { "id":"00001", } And json_decode( $json, false ) should be.
working solution:
$json = '{
"result":0,
"status":[{"id":"00001"},
{"id":"00002"},
{"id":"00003"}
]
}';
$data = json_decode($json, false);
foreach ($data->status as $status){
echo $status->id;
}
You can just use array_column
to extract the id
values from the status
element of your JSON (once it is corrected by removing the superfluous commas):
$ids = array_column(json_decode($json, true)['status'], 'id');
print_r($ids);
Output:
Array (
[0] => 00001
[1] => 00002
[2] => 00003
)