Question

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.)

Was it helpful?

Solution

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>';

}

?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top