PHP:如何从递归函数返回多维数组

时间:2012-10-17 22:58:35

标签: php recursion

这是我的代码, 我需要你的帮助来理解它。

<?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()),
        )),
    )),
)),

);

我需要的是一个递归函数,它将返回所有名称(名称)。 例如:

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

........

我的尝试但它似乎对我不起作用

function tree($tree){ 
    foreach ($tree as $key =>$value) { 
         foreach ($value as $key=>$value){ 
            echo "$value<br>"; } 
    echo "<br>"; } }

2 个答案:

答案 0 :(得分:1)

您可以使用RecursiveArrayIteratorRecursiveIteratorIterator

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

输出

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

答案 1 :(得分:0)

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

另见Sum integers in 2d array using recursion?