我有一个包含这些记录的数据库表:
parent_id child_id
0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8
0 9
0 10
0 11
0 12
1 13
1 14
1 15
2 16
2 17
2 18
3 19
3 20
3 21
4 22
4 23
4 24
5 25
5 26
5 27
6 28
6 29
6 30
7 31
7 32
7 33
7 34
1 35
1 36
1 37
1 38
1 39
我想使用递归函数构建父/子的树结构。
function recursion ($parentID, $lvl){
$query = 'SELECT parent_id, child_id FROM ///// WHERE parent_id='.$parentID;
$this->_db->setQuery($query);
$this->_db->query();
$records = $this->_db->loadObjectList();
$count = count($records);
if ($count > 0){
foreach ($records as $item){
print_r ("parent id ".$item->parent_id."child id ".$item->child_id." lvl-> ".$lvl."</br>");
return $this->recursion($item->child_id, $lvl+1);
}
}
}
我的代码只打印:
parent id 0child id 1 lvl-> 1
parent id 1child id 13 lvl-> 2
我无法弄清楚如何打印整棵树。我想我正走在正确的道路上。有人能给我一个关于如何打印整棵树的提示吗?
答案 0 :(得分:1)
如果要打印整个树,请不要使用递归。
制作正确的一个SQL查询,然后右键输出您需要的内容。
如果您想了解更多有关您想要获得的信息,可以更轻松地为您提供帮助。
感谢。
答案 1 :(得分:1)
删除返回。
下次拿一张纸,逐行浏览代码。写下会发生什么。想一想。
现在,如果您想给老师留下深刻印象,请弄清楚如何在没有递归的情况下执行此操作。大多数递归函数都可以是程序性的,它使用的内存更少。