PHP嵌套集-多维数组
因此,我一直在寻找一种在mysql中实现嵌套类别的好方法,并偶然发现了这篇文章:PHP嵌套集-多维数组,php,mysql,arrays,multidimensional-array,nested-sets,Php,Mysql,Arrays,Multidimensional Array,Nested Sets,因此,我一直在寻找一种在mysql中实现嵌套类别的好方法,并偶然发现了这篇文章: http://falsinsoft.blogspot.com/2013/01/tree-in-sql-database-nested-set-model.html 现在我正在努力生成嵌套数组。我需要生成一个如下所示的数组 Array ( [0] => Array ( [id] => 1, [name] => Electronics [childre
http://falsinsoft.blogspot.com/2013/01/tree-in-sql-database-nested-set-model.html
现在我正在努力生成嵌套数组。我需要生成一个如下所示的数组
Array
(
[0] => Array
(
[id] => 1,
[name] => Electronics
[children] => Array
(
[0] => Array
(
[id] => 2,
[name] => Televisions
[children] => Array (...)
)
)
)
[1] => Array
(
[id] => 5,
[name] => Another Parent category
[children] => Array
(
[0] => Array
(
[id] => 6,
[name] => Child category
[children] => Array (...)
)
)
)
)
这个问题已经有了解决方案,但该函数不能处理多个根类别。其他根类别将被忽略
function create_tree($results) {
$return = $results[0];
array_shift($results);
if ($return['lft'] + 1 == $return['rgt'])
$return['leaf'] = true;
else {
foreach ($results as $key => $result) {
if ($result['lft'] > $return['rgt'])
break;
if ($rgt > $result['lft'])
continue;
$return['children'][] = create_tree(array_values($results));
foreach ($results as $child_key => $child) {
if ($child['rgt'] < $result['rgt'])
unset($results[$child_key]);
}
$rgt = $result['rgt'];
unset($results[$key]);
}
}
unset($return['lft'],$return['rgt']);
return $return;
}
您需要显示您尝试过的代码。显示来自db的收入数据原始数组。
Array
(
[0] => Array
(
[id] => 1
[title] => ELECTRONICS
[description] =>
[lft] => 1
[rgt] => 20
[depth] => 0
)
[1] => Array
(
[id] => 2
[title] => TELEVISIONS
[description] =>
[lft] => 2
[rgt] => 9
[depth] => 1
)
[2] => Array
(
[id] => 3
[title] => TUBE
[description] =>
[lft] => 3
[rgt] => 4
[depth] => 2
)
[3] => Array
(
[id] => 4
[title] => LCD
[description] =>
[lft] => 5
[rgt] => 6
[depth] => 2
)
[4] => Array
(
[id] => 5
[title] => PLASMA
[description] =>
[lft] => 7
[rgt] => 8
[depth] => 2
)
[5] => Array
(
[id] => 12
[title] => Parent
[description] =>
[lft] => 21
[rgt] => 24
[depth] => 0
)
[6] => Array
(
[id] => 14
[title] => Child
[description] =>
[lft] => 22
[rgt] => 23
[depth] => 1
)
)