Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multidimensional Arrays Nested to Unlimited Depth

Tags:

php

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(){foreach(){}}} as I don't know the depth.

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

like image 239
stevenmc Avatar asked Nov 30 '10 10:11

stevenmc


3 Answers

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.

like image 113
salathe Avatar answered Oct 05 '22 22:10

salathe


Recursion.

Write a function that walks one array; for each element that is also an array, it calls itself; otherwise, when it finds the target string, it returns.

like image 41
tdammers Avatar answered Oct 05 '22 23:10

tdammers


There is a vast difference between unknown and unlimited. However, you can make use of the SPL Iterators instead of using multiple nested foreach loops.

Example:

$array_obj = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($array_obj as $key => $value) {
   echo $value;
}
like image 43
Russell Dias Avatar answered Oct 06 '22 00:10

Russell Dias