构建带空格的递归树
有棵树 $id =>数组中的 $children:
$tree = array(
1 => array(
2 => array(),
3 => array(
4 => array()
)
)
);
我需要通过 id 来回显这棵树,每个级别前面都有空格:
1
2
3
4
我使用这个函数:
function build_tree($node)
{
static $space = '';
$space .= '     ';
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当你递归时,你需要向下传递级别:
You need to pass the level downward as you recurse:
您需要跟踪您当前所处的级别:
you need to track the level you are currently in: