title: Disqus-like comment thread logic in PHP
body: <p>I'm trying to make a commenting thread like Disqus has done. I'm having trouble setting up the logic in PHP to display the comments such that one can reply to each comment and those comments will then stay attached to each other.</p>
  
  <p>here's my MySQL comments table:</p>
  
  <pre><code>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
  </code></pre>
  
  <p><code>item_id</code> is a column which indicates the parent item that the comments are discussing.</p>
  
  <p>If I pull from my database all the comments with <code>item_id=1</code>, then I'm not sure how to thread them such that the <code>comment_id</code> and <code>replied_to_id</code>'s are appropriately matched. For example, <code>comment_id=2</code> should be matched to <code>comment_id=1</code>.</p>
  
  <p>Here's my PHP:</p>
  
  <pre><code>&lt;?foreach($comments as $row){
    if($row-&gt;comment_id==$row-&gt;replied_to_id){
      echo $row-&gt;comment."-".$row-&gt;time; //desired output: hello1-1:00pm    
        foreach($comments as $sub_row){
          if($row-&gt;comment_id!=$sub_row-&gt;replied_to_id){
             echo $sub_row-&gt;comment."-".$sub_row-&gt;time;// desired output: hello2-2:00pm
               foreach($comments as $sub_sub_row){
                  if($row-&gt;comment_id!=$sub_sub_row-&gt;replied_to_id){
                    echo $sub_sub_row-&gt;comment."-".$sub_sub_row-&gt;time;// desired output: hello5-5:00pm  
                  }
               } 
          }
       }          
    }
    else{
      echo $row-&gt;comment."-".$row-&gt;time;   // desired output: hello3-3:00pm
    }
  }
  </code></pre>
  
  <p>This just looks wrong. There has got to be a better way to do this.</p>