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

1

1 Answer 1

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

}

?>
Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.