2009-11-19 95 views
0
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 
+3

您遍歷$孩子,但那麼你遍歷每個後續遞歸調用_same_ $孩子陣列。你想傳遞一個不同的兒童價值的遞歸函數? – 2009-11-19 18:29:29

回答

1

當我在你列出的數據運行功能,我得到你所描述的順序,但我不缺少任何物品:

id: 1, pid:0 
id: 2, pid:1 
id: 3, pid:2 
id: 5, pid:3 
id: 6, pid:5 
id: 8, pid:3 
id: 4, pid:1 
id: 7, pid:4 

而且這個結果其實是你想要的樹結構,只是按照ID的順序排列。如果你爲你的chhildren陣列由ID的下降,那麼你實際上得到你要求的輸出:

id: 1, pid:0 
id: 4, pid:1 
id: 7, pid:4 
id: 2, pid:1 
id: 3, pid:2 
id: 8, pid:3 
id: 5, pid:3 
id: 6, pid:5 

你應該確保你在從DB降序排列數據。對於這種非DB測試用例,我固定它通過調用find_children()之前使用以下物質:

function revCmpObjects($a, $b) { //Just a basic descending ordering by the id 
    if ($a->id == $b->id) { 
     return 0; 
    } 
    return ($a->id > $b->id) ? -1 : 1; 
} 
usort($children, 'revCmpObjects'); //The actual sorting 
+0

這裏是我認爲應該顯示的節點(如果我能得到工作的功能) ID 1,PID 0 - ID 2,PID 1 - ID 3,PID 2 --- ID 5,PID 3 ---- id 6,pid 5 - id 4,pid 1 - id 7,pid 4 注意到,儘管節點4在我的列表和節點2以及它的所有子節點中位於第二位高於它。 – Brad 2009-11-19 21:18:01

+0

沒關係,那沒有格式正確。 – Brad 2009-11-19 21:18:32

+0

你在列表中忘記了ID:9,但是如果你在ID:3和ID:5之間添加了那個,那麼你有我發佈的第一個輸出。所以我認爲你需要進一步清理。它實際上只是要添加到每個節點的樹深度? – allanmc 2009-11-19 21:42:25