Is there a way to loop through a multidimensional array without knowing it's depth?

后端 未结 5 1761
滥情空心
滥情空心 2020-12-01 16:39

So far, if I have to loop through a multidimensional array, I use a foreach loop for each dimension.

e.g for two dimensions

foreach($array as $key=&g         


        
5条回答
  •  长情又很酷
    2020-12-01 17:23

    Based on previous recursion examples, here is a function that keeps an array of the path of keys a value is under, in case you need to know how you got there:

    function recurse($a,$keys=array()) 
        {
            if (!is_array($a)) 
                {
                    echo implode("-", $keys)." => $a 
    "; return; } foreach($a as $k=>$v) { $newkeys = array_merge($keys,array($k)); recurse($v,$newkeys); } } recurse($array);

提交回复
热议问题