private function find_children ($parent_id, $children, &$result)
{
foreach ($children as $c)
{
if ($c->parent_comment_id == $parent_id)
{
$result[] = $c;
$this->find_children($c->id, $children, $result);
}
}
return;
}
上述功能應該採取啓動父ID和遞歸經過子節點的數組(實際上只是一個唯一的ID和父ID的對象)對它們進行排序以便每個節點都直接位於父節點之後(請參閱下面的示例數據)。遞歸功能無法正常運行
但由於某種原因,該函數沒有按照我的預期執行。我有以下數據進行測試。
id: 1 pid: 0 (the initial parent which is not in the children array passed to func. problem?)
id: 2 pid: 1
id: 3 pid: 2
id: 4 pid: 1
id: 5 pid: 3
id: 6 pid: 5
id: 7 pid: 4
id: 8 pid: 3
,並希望以下數組返回: 1,4,7,2,3,8,5,6
但是相反,我得到: 1,2,3,5,6
哪些,雖然他們是在正確的順序,少數失蹤。
我沒有多少年需要做遞歸,所以很可能我錯過了一些明顯的東西,儘管對我自己來說並不那麼明顯。
如果有人想知道,或者它很重要,我試圖建立一個評論系統,每個帖子可以有多個回覆。
這樣:
initial post
-reply to initial post #1
--reply to reply
-reply to initial post #2
-- reply to above
--- reply to above
--reply to #2
您遍歷$孩子,但那麼你遍歷每個後續遞歸調用_same_ $孩子陣列。你想傳遞一個不同的兒童價值的遞歸函數? – 2009-11-19 18:29:29