将树数据放入数组的有效方法是什么?
我按照sitepoint教程检索树数据.
但是,本教程仅显示如何输出树,而不是如何创建多个数组.
我用了
SELECT title, lft, rgt FROM tree_structure WHERE lft BETWEEN $parentLft AND $parentRgt ORDER BY lft ASC
Run Code Online (Sandbox Code Playgroud)
所以对于每个项目,我都有它的标题,左右值.
我坚持让阵列看起来像这样
Array
(
Title: Main Topic
Children => Array
(
=> Title: subTopic
Leaf: true
=> Title: Another subtopic
Children => Array
(
=> Title: subtopic child
Leaf: true
)
)
)
Run Code Online (Sandbox Code Playgroud)
如果你能提供帮助,我会非常感激.
PS.sql输出看起来像这样(除了我有标题,不是名称,不使用category_id):
+-------------+----------------------+-----+-----+
| category_id | name | lft | rgt |
+-------------+----------------------+-----+-----+
| 1 | ELECTRONICS | 1 | 20 |
| 2 | TELEVISIONS | 2 | 9 |
| 3 | TUBE | 3 | 4 |
| 4 | LCD | 5 | 6 |
| 5 | PLASMA | 7 | 8 |
| 6 | PORTABLE ELECTRONICS | 10 | 19 |
| 7 | MP3 PLAYERS | 11 | 14 |
| 8 | FLASH | 12 | 13 |
| 9 | CD PLAYERS | 15 | 16 |
| 10 | 2 WAY RADIOS | 17 | 18 |
Run Code Online (Sandbox Code Playgroud)
给这个代码一个机会.$ results是数据库结果.$ tree是你要回来的数组.
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']) //not a child
break;
if ($rgt > $result['lft']) //not a top-level child
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;
}
$tree = create_tree($results);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4241 次 |
| 最近记录: |