mardi 5 mai 2015

Recursing through a PHP array and producing the array tree as output

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?

Aucun commentaire:

Enregistrer un commentaire