Nested array with one foreach loop?

I need to be able to access an array that looks like this.

Array
(
    [0] => Array
        (

            [54] => Array
            (
                [test] => 54
                [tester] => result
            )
         )
)

foreach($array as $key=>$value)
{
  echo $key;// prints 0
  echo $value;// prints Array
  /*
   now i can iterate through $value but i dont want it solve that way example:
  foreach($value as $k=>$v)
  {
    echo $k;//prints test
    echo $v; //prints 54
  }
  */

}

      

How can you only repeat it once? to get test and tester values ? Hope I can explain my problem in a clear way.

+2


a source to share


3 answers


Use SPL RecursiveDirectoryIterator

$iterator = new RecursiveIteratorIterator(
                new RecursiveArrayIterator($array), 
                RecursiveIteratorIterator::SELF_FIRST);

foreach($iterator as $key => $val) {
    if($key === 'test' || $key === 'tester') {
        echo "$key = $val \n";
    }
}

      

All elements of the array with the test or tester value will be found here, regardless of where it appears in the multidimensional array. If you need to narrow it down to a specific depth in the array, you can map it to $iterator->getDepth()

.


You can also put an if condition in the body of the FilterIterator > accept () method , for example



class TestFilter extends FilterIterator
{
    public function accept()
    {
        return ($this->key() === 'test' || $this->key() === 'tester');
    }
}

      

and then wrap an iterator in it before foreach

, for example

$iterator = new TestFilter($iterator); // wrap iterator from first example
foreach($iterator as $key => $val) {
    echo "$key = $val \n";    
}

      

Further reading:

+4


a source


You can use an anonymous function to enumerate items. This will use recursion every time the array is encountered as an element:

array_walk_recursive($array, create_function('$item, $key', 
    'echo "$key => $item<br />";'
));

      

Or when using PHP 5.3:

array_walk_recursive($array, function($item, $key) { 
    echo "$key => $item<br />";
});

      



It will be faster (and more readable) than create_function (). However, this construct is only available in PHP 5.3 and higher.

Both output:

test => 54
tester => result

      

This is exactly what you want, I believe.

+1


a source


This will only work for this particular array:

foreach($array[0][54] as $key=>$value)
{
    echo $key;// prints test and tester
    echo $value;// prints 54 and result
}

      

0


a source







All Articles