Walk array recursively and print the path of the walk

前端 未结 9 1498
礼貌的吻别
礼貌的吻别 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 came up with the following function based on @salathe's one. It returns an array where each element is an array containing the leaf at index 0 and the array of the path keys at index 1:

    function loosenMultiDimensionalArrayPathForEachVal($array) {
        $iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($array), \RecursiveIteratorIterator::SELF_FIRST);        
        $iterator->rewind();
        $res = [];
        foreach ($iterator as $v) {
            $depth = $iterator->getDepth();
            for ($path = array(), $i = 0, $z = $depth; $i <= $z; $i++) {
                $path[] = $iterator->getSubIterator($i)->key();
            }
            $leaf = $array;
            foreach ($path as $pathKey) {
                $leaf = $leaf[$pathKey];
            }
            if (!is_array($leaf)) {
                $res[] = [
                    $v,
                    $path
                ];
            }
        }
        return $res;
    }
    

    The main reason I implemented this one is that $iterator->hasChildren() returns true if the current iterated leaf is an object. Therefore, I wouldn't be able to get the path of it that way.

提交回复
热议问题