Walk array recursively and print the path of the walk

前端 未结 9 1491
礼貌的吻别
礼貌的吻别 2020-12-03 08:03

Can someone help me with some code or instructions on how to walk recursively an array and when reaching the last element print the full path to it? A simple echo will work

9条回答
  •  抹茶落季
    2020-12-03 08:44

    I had similar problem. Here is a Depth-First Search-ish solution(no path depth included, it reaches until the very end of the array). Comment the 'if' statement if u don't want to include the value:

    $output = array();
    retrievePath($someArray, $output);
    
    function retrievePath($someArray, array &$pathKeeper)
    {
        if(!is_array($someArray)){ // $someArray == "end"
            $element = array_pop($pathKeeper) ?? '';// if the array is empty pop returns null, we don't want that
            array_push($pathKeeper, $element . '->'. $someArray);
        } else{
            end($someArray);//we want to get the last element from the array so we move the internal pointer to it's end
            $endElKey = key($someArray);//take the key where the pointer is
            reset($someArray);
            foreach($someArray as $key=>$value){
                $element = array_pop($pathKeeper);
                array_push($pathKeeper, $element === null ? $key : $element . '->' . $key);// we don't want '->' at the beginning
                retrievePath($value, $pathKeeper);
                if($key != $endElKey) //we check whether this is not the last loop
                    array_push($pathKeeper, $element);
            }
        }
    }
    

提交回复
热议问题