这里是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}}
这是我的代码:
$json = json_decode($data); foreach($json["result"] as $result){ foreach($result["files"] as $file){ echo $file["file_code"]; } }
我想从"file_code"中提取所有值。我收到一个错误警告:为foreach()提供的参数无效
将$json['result']
视为对象,因此下一行测试total_pages["files"]
,它不存在。
将两个foreach
放在一起可以解决问题:
$data='{"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}}'; $json = json_decode($data, true); foreach($json["result"]["files"] as $file) print $file["file_code"];
或者,将JSONresult
放入数组,并使用对象属性访问器而不是关联数组绑定。
$data='{"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}]}'; $json = json_decode($data); foreach($json->result as $result){ foreach($result->files as $file){ echo $file->file_code; } }
标签: PHP