13

I have an array like this:

$arr = array(
        $foo = array(
            'donuts' => array(
                    'name' => 'lionel ritchie',
                    'animal' => 'manatee',
                )
        )
    );

Using that magic of the 'SPL Recursive Iterator' and this code:

$bar = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));

    foreach($bar as $key => $value) 
    {
        echo $key . ": " . $value . "<br>";
    }

I can traverse the multidimensional array and return the key => value pairs, such as:

name: lionel ritchie animal: manatee

However, I need to return the PARENT element of the current iterated array as well, so...

donuts name: lionel richie donuts animal: manatee

Is this possible?

(I've only become aware of all the 'Recursive Iterator' stuff, so if I'm missing something obvious, I apologise.)

Captain flapjack
  • 426
  • 6
  • 16
  • possible duplicate of [Get array's key recursively and create underscore seperated string](http://stackoverflow.com/questions/2749398/get-arrays-key-recursively-and-create-underscore-seperated-string) – salathe Jun 01 '13 at 12:07

1 Answers1

17

You can access the iterator via getSubIterator, and in your case you want the key:

<?php

$arr = array(
    $foo = array(
        'donuts' => array(
                'name' => 'lionel ritchie',
                'animal' => 'manatee',
            )
    )
);
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));

foreach ($iterator as $key => $value) {
    // loop through the subIterators... 
    $keys = array();
    // in this case i skip the grand parent (numeric array)
    for ($i = $iterator->getDepth()-1; $i>0; $i--) {
        $keys[] = $iterator->getSubIterator($i)->key();
    }
    $keys[] = $key;
    echo implode(' ',$keys).': '.$value.'<br>';

}

?>
axel.michel
  • 5,764
  • 1
  • 15
  • 25