简体   繁体   English

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

[英]How do I loop through multidimensional JSON array in PHP?

I want to write code to loop through a multidimensional array (4 or 5 deep) and echo all keys and values found and skip empty arrays.我想编写代码来循环遍历多维数组(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) 
...

Anyone, anyone, Ferris?任何人,任何人,费里斯?

Your $data_drugs is no longer a json, after json_decode is an associative array.在 json_decode 是关联数组之后,您的 $data_drugs 不再是 json。
You don't need any loop to see keys and values你不需要任何循环来查看键和值

$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>';

You can use var_dump($data_drugs) - keys and values with types, probably you don't need this您可以使用var_dump($data_drugs) - 带有类型的键和值,可能您不需要这个
But if you want to display keys and values more ...fancy use a recursive function但是如果你想更多地显示键和值......花式使用递归函数

function show($x){
    foreach($x as $key=>$val){
        echo"<p>$key : ";
        if(is_array($val)){ echo". . ."; show($val);}
        else{ echo"$val</p>";}}}

show($data_drugs);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM