【发布时间】:2012-07-27 14:27:07
【问题描述】:
我正在尝试将扁平的 mysql 行转换为树结构。
$categories = array(
array(
'id' => '1',
'name' => 'root',
'parent' => '0',
),
array(
'id' => '2',
'name' => 'first',
'parent' => '1',
),
array(
'id' => '3',
'name' => 'first',
'parent' => '1',
),
array(
'id' => '4',
'name' => 'second',
'parent' => '3',
),
);
我先初始化所有一级节点,然后在每个节点上调用build_tree。
$hierarchy = array();
// loop through and get each root node
foreach($categories as $key => $category) {
if ($category['parent'] == 0) {
// initialize this root
$hierarchy[$category['id']] = $category;
$hierarchy[$category['id']]['children'] = array();
// remove this from categories
unset($categories[$key]);
$this->build_tree($hierarchy[$category['id']], $categories);
}
}
return $hierarchy;
}
function build_tree(&$node, &$categories) {
foreach ($categories as $key => $category) {
// check if this node is the parent
if ($node['id'] === $category['parent']) {
$node['children'][$category['id']] = $category;
$node['children'][$category['id']]['children'] = array();
unset($categories[$key]);
$this->build_tree($category, $categories);
}
}
}
这只是返回树的第一层和第二层。
array
1 =>
array
'id' => string '1' (length=1)
'name' => string 'root' (length=4)
'parent' => string '0' (length=1)
'children' =>
array
2 =>
array
'id' => string '2' (length=1)
'name' => string 'first' (length=5)
'parent' => string '1' (length=1)
'children' =>
array
empty
3 =>
array
'id' => string '3' (length=1)
'name' => string 'first' (length=5)
'parent' => string '1' (length=1)
'children' =>
array
empty
在build_tree 内部,当它到达id=2 时,它正在成功创建子代。 (发现有一个 id=2 的孩子并将其正确附加到 'children' )
只是没有保存它!谁能看到我做错了什么?当我var_dump 层次结构时,即使在build_tree 中成功创建了第三层,它也只是第一层和第二层,而不是第三层。任何帮助将不胜感激。泰。
【问题讨论】:
-
我发现在编写递归函数时,向后工作更有效——先编写转义案例,然后编写延续案例——这就是你开发此函数的方式吗?
-
我猜你需要在这里循环引用:
foreach ($categories as $key => &$category) {。注意添加了&。这样能解决吗? -
@nickb 不,没有解决它,马特没有机智地开发它,只是摸索了几个小时,当我终于得到第一和第二级时,我只是试图用它滚动.我会先尝试编写转义案例,ty
-
Sample code 应该是完整的。给定的代码缺少第一个方法中的一些行以及示例数据(作为 PHP 数组)和启动它的方法调用。