猿问

如何在 PHP 中循环多维 JSON 数组?

我想编写代码来循环遍历多维数组(4 或 5 深)并回显找到的所有键和值并跳过空数组。


$drugs = fopen("http://dgidb.org/api/v2/interactions.json?drugs=FICLATUZUMAB", "r");

$json_drugs = stream_get_contents($drugs);

fclose($drugs);

$data_drugs = json_decode($json_drugs,true);


foreach ($data_drugs as $key => $value) 

...

有人吗,有人吗,费里斯?


phpjson解析


桃花长相依
浏览 121回答 1
1回答

汪汪一只猫

在 json_decode 是关联数组之后,您的 $data_drugs 不再是 json。您不需要任何循环来查看键和值$data_drugs = json_decode($json_drugs,true);print_r($data_drugs);/* or if you don't like inline */echo'<pre>';print_r($data_drugs);echo'</pre>';您可以使用var_dump($data_drugs)- 键和值与类型,可能您不需要这个但是如果您想更多地显示键和值...喜欢使用递归函数function show($x){&nbsp; &nbsp; foreach($x as $key=>$val){&nbsp; &nbsp; &nbsp; &nbsp; echo"<p>$key : ";&nbsp; &nbsp; &nbsp; &nbsp; if(is_array($val)){ echo". . ."; show($val);}&nbsp; &nbsp; &nbsp; &nbsp; else{ echo"$val</p>";}}}show($data_drugs);
随时随地看视频慕课网APP
我要回答