我正在尝试将扁平的 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
. 任何帮助将不胜感激。泰。