将修改后的预排序树遍历数据放入数组 [英] Getting Modified Preorder Tree Traversal Data into an Array
问题描述
将树数据放入数组的有效方法是什么?
What is an efficient way to put the tree data into an array?
我遵循了站点指南来检索树数据.
I followed the sitepoint tutorial to retrieve the tree data.
但是,本教程仅显示如何输出树,而不显示如何创建多维数组.
However, the tutorial only shows how to output the tree, not how to make a multidementional array.
我用过
SELECT title, lft, rgt FROM tree_structure WHERE lft BETWEEN $parentLft AND $parentRgt ORDER BY lft ASC
因此,对于每个项目,我都有其标题,左侧和右侧的值.
So for each item, I have its title, left and right values.
我一直坚持让数组看起来像这样
I am stuck on making the array look like this
Array
(
Title: Main Topic
Children => Array
(
=> Title: subTopic
Leaf: true
=> Title: Another subtopic
Children => Array
(
=> Title: subtopic child
Leaf: true
)
)
)
如果您能提供帮助,我将非常感谢.
If you could help, I would really appreciate it.
PS. sql输出看起来像这样的 (除了我有标题,没有名称,不要使用category_id):
PS. The sql output looks like this (except I have title, not name and don't use 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 |
推荐答案
将此代码提供帮助. $ results是数据库结果. $ tree是您要返回的数组.
Give this code a shot. $results is the database results. $tree is the array you're getting back.
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);
这篇关于将修改后的预排序树遍历数据放入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!