How do I loop through multidimensional JSON array in PHP?

百般思念 提交于 2021-02-11 12:39:48

问题


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.

$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?


回答1:


Your $data_drugs is no longer a json, after json_decode is an associative array.
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
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);


来源:https://stackoverflow.com/questions/63637498/how-do-i-loop-through-multidimensional-json-array-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!