构建带空格的递归树

发布于 2024-10-20 11:50:22 字数 682 浏览 2 评论 0原文

有棵树 $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

那么,我怎样才能制作空格每个级别都相同?

There is a tree $id => $children in array:

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

I need to echo this tree by id with spaces in front of each level:

1
    2
    3
        4

I use this function:

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

    $space .= '     ';

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

build_tree($tree);

But i couldn't handle spaces, they just added each iteration and result is:

1
    2
        3
            4

So, how can I make spaces to be the same for each level?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

疑心病 2024-10-27 11:50:22

当你递归时,你需要向下传递级别:

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

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

build_tree($tree);

You need to pass the level downward as you recurse:

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

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

build_tree($tree);
日裸衫吸 2024-10-27 11:50:22

您需要跟踪您当前所处的级别:

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

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

build_tree($tree, 0);

you need to track the level you are currently in:

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

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

build_tree($tree, 0);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文