1
PHP 5.4

My code (based on the manual):

<?php
$myArray = array(
    'level_1' => array(
        1,
        'level_2' => array(
            2
        )
    )
);

$iterator = new RecursiveArrayIterator($myArray); 
iterator_apply($iterator, 'traverseStructure', array($iterator)); 

function traverseStructure($iterator) { 
    while ( $iterator -> valid() ) {
        if ( $iterator -> hasChildren() ) {        
            traverseStructure($iterator -> getChildren());            
        } 
        else { 
            echo $iterator -> key() . ' : ' . $iterator -> current() ."</br>";    
        } 
        $iterator -> next(); 
    } 
} 

Here's my output:

0 : 1
0 : 2

Here's what I would like to see:

level_1 : 0 : 1
level_1 : level_2 : 0 : 2

Any ideas?

1 Answer 1

1

Explanation: You can't achieve what you desire without passing down the parent_iterator, so amend the traverseStructure() to cater for that.

Code:

<?php
$myArray = array(
    'level_1' => array(
        1,
        'level_2' => array(
            2
        )
    )
);

$iterator = new RecursiveArrayIterator($myArray); 
iterator_apply($iterator, 'traverseStructure', array($iterator, '')); 

function traverseStructure($iterator, $parent_iterator) {
    while ( $iterator->valid() ) {

        // If the parent is available, print out the key also
        if ($parent_iterator) {
            echo $parent_iterator->key().' : ';
        }

        if ( $iterator->hasChildren() ) {
            traverseStructure($iterator->getChildren(), $iterator);
        } 
        else { 
            echo $iterator->key() . ' : '.$iterator->current() . "<br>";
        }
        $iterator->next();
    }
}

?>

Outputs:

level_1 : 0 : 1<br>level_1 : level_2 : 0 : 2<br>
Sign up to request clarification or add additional context in comments.

Comments

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.