Multidimensional Arrays Nested to Unlimited Depth

后端 未结 6 1043
被撕碎了的回忆
被撕碎了的回忆 2020-12-06 07:33

I have a multidimensional array nested to an unknown/unlimited depth. I\'d like to be able to loop through every element. I don\'t want to use, foreach(){foreach(){for

6条回答
  •  鱼传尺愫
    2020-12-06 07:59

    I'm eventually looking for all nested arrays called "xyz". Has anyone got any suggestions?

    Sure. Building on the suggestions to use some iterators, you can do:

    $iterator = new RecursiveIteratorIterator(
        new RecursiveArrayIterator($array),
        RecursiveIteratorIterator::SELF_FIRST
    );
    foreach ($iterator as $key => $item) {
        if (is_array($item) && $key === 'xyz') {
            echo "Found xyz: ";
            var_dump($item);
        }
    }
    

    The important difference between the other answers and this being that the RecursiveIteratorIterator::SELF_FIRST flag is being employed to make the non-leaf (i.e. parent) items (i.e. arrays) visible when iterating.

    You could also make use of a ParentIterator around the array iterator, rather than checking for arrays within the loop, to make the latter a little tidier.

提交回复
热议问题