0

This is my code, and I need your help to understand it.

<?php $tree = array(
array(
    'name' => 'Item-1', 
    'children' => array()),

array('name' => 'Item-2', 
    'children' => array(
    array('name' => 'Item-2-1', 
        'children' => array()),
)),
array('name' => 'Item-3', 
    'children' => array(
    array('name' => 'Item-3-1', 
        'children' => array()),

    array('name' => 'Item-3-2', 
        'children' => array(
        array('name' => 'Item-3-2-1', 
            'children' => array()),

        array('name' => 'Item-3-2-2', 
            'children' => array()),

        array('name' => 'Item-3-2-3', 
            'children' => array(
            array('name' => 'Item-3-2-3-1', 
                'children' => array()),
        )),
    )),
)),

);

What i need is one recursive function, which will return all names (name). For example:

Item-1
Item-2
Item-2-1
Item-3
Item-3-1
Item-3-2

........

My attempt but it just doesn't seem to work for me

function tree($tree){ 
    foreach ($tree as $key =>$value) { 
         foreach ($value as $key=>$value){ 
            echo "$value<br>"; } 
    echo "<br>"; } }
2
  • You need our help in making you understand your own code? Commented Oct 17, 2012 at 23:09
  • I would say that you should first start reading about PHP. You are not having a problem with some code, you look like haven't even tried to do anything. Commented Oct 17, 2012 at 23:09

2 Answers 2

1

You can use RecursiveArrayIterator and RecursiveIteratorIterator

$ai = new RecursiveIteratorIterator(new RecursiveArrayIterator($tree));
echo "<pre>";
foreach ( $ai as $value ) {
    echo $value, PHP_EOL;
}

Output

Item-1
Item-2
Item-2-1
Item-3
Item-3-1
Item-3-2
Item-3-2-1
Item-3-2-2
Item-3-2-3
Item-3-2-3-1

See Live Demo

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

Comments

0

From http://snipplr.com/view/10200/

// Recursively traverses a multi-dimensional array.
function traverseArray($array)
{ 
    // Loops through each element. If element again is array, function is recalled. If not, result is echoed.
    foreach($array as $key=>$value)
    { 
        if(is_array($value))
        { 
            traverseArray($value); 
        }else{
            echo $key." = ".$value."<br />\n"; 
        } 
    }
}

Also see Sum integers in 2d array using recursion?

Comments

Your Answer

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