PHP按指定的深度和规则生成一棵树 [英] PHP generate a tree by specified depth and rules
本文介绍了PHP按指定的深度和规则生成一棵树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我坚持使用树生成算法:
I'm stuck with a tree generating algorithm:
- 没有父子参数,只有起始节点值
- 每个节点都有 2 个子节点(最后一个子节点除外)
数组示例:
$start = 1;
$depth = 3;
$s = array(
'name' => 1, // taken from $start
'children' => array(
array(
'name' => 2,
'children => array(
array( 'name' => 3 ), /* No children for last node $depth */
array( 'name' => 3 ), /* No children for last node $depth */
)
),
array(
'name' => 2,
'children => array(
// same as above
)
),
)
);
在这一点上,我想出了一个非常丑陋的函数,希望得到任何帮助或建议来构建更漂亮的算法.
At this point I've come up with a very ugly function and would appreciate any help or suggestions to build more nice algorithm.
推荐答案
这应该会有所帮助
function generateTree($depth, $level = 0)
{
$result = array();
if ($depth == $level) {
$result = array('name' => $level);
} else {
$result = array('name' => $level, 'children' => array(generateTree($depth, $level + 1), generateTree($depth, $level + 1)));
}
return $result;
}
print_r(generateTree(3, 1));
这篇关于PHP按指定的深度和规则生成一棵树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文