用空格构建递归树

时间:2011-03-05 18:30:45

标签: php recursion

有一棵树$ id =>数组中的$ children:

$tree = array(
    1 => array(
        2 => array(),
        3 => array(
            4 => array()
        )
    )
);

我需要通过id在每个级别前面用空格回显这个树:

1
    2
    3
        4

我使用这个功能:

function build_tree($node)
{
    static $space = '';

    $space .= ' &nbsp &nbsp ';

    foreach ($node as $id => $children)
    {
        echo $space.$id.'<br />';
        build_tree($children);
    }
}

build_tree($tree);

但我无法处理空格,他们只是添加了每次迭代,结果是:

1
    2
        3
            4

那么,我怎样才能让每个级别的空格相同?

2 个答案:

答案 0 :(得分:2)

你需要在递归时向下传递关卡:

function build_tree($node, $level=0) {
    static $space = ' &nbsp  &nbsp ';

    foreach ($node as $id => $children) {
        echo str_repeat($space, $level).$id.'<br />';
        if ($children) build_tree($children, $level+1);
    }
}

build_tree($tree);

答案 1 :(得分:1)

您需要跟踪目前的级别:

function build_tree($node, $level = 0)
{
    $space = str_repeat(' &nbsp &nbsp ', $level);

    foreach ($node as $id => $children)
    {
        echo $space.$id.'<br />';
        if(is_array($children))
          build_tree($children, $level+1);
    }
}

build_tree($tree, 0);