Here's the json
{"msg":"OK","server_time":"2021-11-19 16:41:22","status":200,"result":{"total_pages":1,"files":[{"download_url":"DOWNLOADLINKHERE1","single_img":"IMAGEURLHERE1","file_code":"CODEHERE1","title":"TITLEHERE1"},{"download_url":"DOWNLOADLINKHERE2","single_img":"IMAGEURLHERE2","file_code":"CODEHERE2","title":"TITLEHERE2"}],"results_total":"2","results":2}}
Here's my code
$json = json_decode($data);
foreach($json["result"] as $result){
foreach($result["files"] as $file){
echo $file["file_code"];
}
}
I want to extract all values from the "file_code". I got an error Warning: Invalid argument supplied for foreach()
I was able get the VALUE of the first one using
echo $json->result->files[0]->file_code;
Is it possible to use a LOOP for the files[0]?
CodePudding user response:
I replicated your situation and it turns out that your JSON is invalid. You're missing a }
at the end.
The reason for not getting an exception is because json_decode
does not throw an error by default. You can make it do so by adding the JSON_THROW_ON_ERROR
flag,
read the docs for more info.
CodePudding user response:
This works perfect for me. If you have any thoughts please feel free to correct me.
$num = count($json->result->files);
echo $num;
for($i=0;$i<$num;$i )
{
echo $json->result->files[$i]->file_code;
}