Iterate through Nested array in PHP

风流意气都作罢 提交于 2019-12-30 12:13:47

问题


I have a nested array on this link Array Sample

I am using code below to parse this, but second and beyond depth it's returning nothing. However tried with recursive function.

printAllValues($ArrXML);

function printAllValues($arr) {
    $keys = array_keys($arr);
    for($i = 0; $i < count($arr); $i++) {
        echo $keys[$i] . "$i.{<br>";
        foreach($arr[$keys[$i]] as $key => $value) {
            if(is_array($value))
            {
                printAllValues($value);
            }
            else
            {
            echo $key . " : " . $value . "<br>";        
           }
        }
        echo "}<br>";
    }
}

What I am doing Wrong? Please help.


回答1:


Version of J. Litvak's answer that works with SimpleXMLElement objects.

function show($array) {
    foreach ($array as $key => $value) {
        if (!empty($value->children())) {
            show($value);
        } else {
            echo 'key=' . $key . ' value=' . $value. "<br>";
        }
    }
}

show($ArrXML);



回答2:


You can use recurcive function to print all values:

function show($array) {
    foreach( $array as $key => $value) {
        if (is_array($value)) {
            show($value);
        } else{
            echo 'key=' . $key . ' value=' . $value. "<br>";
        }
    }
}

show($ArrXML);


来源:https://stackoverflow.com/questions/48295910/iterate-through-nested-array-in-php

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