user1754728
user1754728

Reputation:

PHP: how to return multi dimension array from recursive function

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>"; } }

Upvotes: 0

Views: 231

Answers (2)

twodayslate
twodayslate

Reputation: 2833

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?

Upvotes: 0

Baba
Baba

Reputation: 95161

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

Upvotes: 1

Related Questions