2012-04-30 20 views
0

我正在嘗試做一個像Disqus這樣的評論線程。我無法在PHP中設置邏輯來顯示評論,以便人們可以回覆每條評論,然後這些評論將保持彼此連接。Disqus-like在PHP中的評論線程邏輯

,這裏是我的MySQL意見表:

comment_id comment item_id replied_to_id time 
1   hello1 1   1   1:00pm 
2   hello2 1   1   2:00pm 
3   hello3 1   3   3:00pm 
4   hello4 2   4   4:00pm 
5   hello5 1   2   2:00pm 
6   hello6 1   3   6:00pm 

item_id是表示該意見正在討論的父項列。

如果我從我的數據庫中提取所有與item_id=1的評論,那麼我不確定如何對它們進行線程化,以使comment_idreplied_to_id的匹配得當。例如,comment_id=2應與comment_id=1匹配。

這裏是我的PHP:

<?foreach($comments as $row){ 
    if($row->comment_id==$row->replied_to_id){ 
    echo $row->comment."-".$row->time; //desired output: hello1-1:00pm  
     foreach($comments as $sub_row){ 
     if($row->comment_id!=$sub_row->replied_to_id){ 
      echo $sub_row->comment."-".$sub_row->time;// desired output: hello2-2:00pm 
      foreach($comments as $sub_sub_row){ 
       if($row->comment_id!=$sub_sub_row->replied_to_id){ 
        echo $sub_sub_row->comment."-".$sub_sub_row->time;// desired output: hello5-5:00pm 
       } 
      } 
     } 
    }   
    } 
    else{ 
    echo $row->comment."-".$row->time; // desired output: hello3-3:00pm 
    } 
} 

這只是看起來是錯誤的。有一個更好的方法來做到這一點。

+1

magic關鍵字是* recursion *。當然,你首先必須理解遞歸...:o) – deceze

+0

感謝Deceze,我認爲遞歸將是關鍵,但不知道如何根據我的參數設置一個簡單的演示。你可以幫忙嗎? –

回答

1

簡單的演示,並不一定是最優的,但工作:

function displayComments(array $comments, $parentId = null) { 
    foreach ($comments as $comment) { 
     if ($comment['replied_to_id'] == $parentId) { 
      echo $comment['comment']; 
      displayComments($comments, $comment['id']); 
     } 
    } 
} 

這是假設頂層的意見沒有replied_to_idnull)。您的示例11的回覆沒有多大意義。

+0

謝謝!是的,評論'1'回答'1'是沒有意義的,更像是我的簿記。如果你沒有這個更容易做出遞歸的例子,我將非常感謝,看看會是什麼樣子。謝謝, –

+0

呃,對不起?上面給出的例子演示了遞歸到輸出線程註釋,忽略當前的'1' ='1',而是假定註釋'1'具有'null'的'replied_to_id'。 – deceze

+0

另一件事是我使用codeigniter和他們的'foreach'速記:'<?的foreach(...):?>'。我不知道如何在你的'displayComments()'函數中包裝這些代碼。我使用這種簡寫形式的原因是因爲實際上,我不僅僅在做一個簡單的'echo $ comment',而且還有相當多的HTML正在呈現。 –