evanct Posted August 12, 2009 Share Posted August 12, 2009 So i'm making a comment/post scheme where replies are indented directly below their parent post, ala reddit/digg. i'm using a recursive function to check if the 'children' field in the sql table for that particular post is greater than 0, and if it is, select the rows where the 'parent' field value is the same as the id of the particular post. <?php $content=''; $a=array(); function getContent() { global $content; global $a; $sql="SELECT * FROM posts ORDER BY votes DESC LIMIT 10"; $result=mysql_query($sql) or die(mysql_error()); while ($row=mysql_fetch_assoc($result)) { $id=$row['post_id']; $a[$id]=$row; } foreach ($a as $post) { // some formatting of the post... // if ($post['children'] != 0) { makeTree($post['post_id']); } } return $content; } function makeTree($id) { global $content; global $a; $content.="<li><ul>"; $sql="SELECT * FROM posts WHERE parent='$id'"; $result=mysql_query($sql); $a2=array(); while ($row=mysql_fetch_assoc($result)) { $a2[]=$row; } foreach ($a2 as $post) { // formatting again... // if ($post['children']!=0) { makeTree($post['post_id']); } } $content.="</ul></li>"; unset($a[$id]); } ?> it's all peachy, except that reply posts appear twice: once in the correct place(indented below their parent), and then again in the main list of posts. like this: #1 #4 (reply) #2 #3 #4 (shouldn't be here) setting the main array of posts as a global, and removing the post from the array at the end of the makeTree function doesn't seem to help. am i missing something? Link to comment https://forums.phpfreaks.com/topic/169986-solved-tree-structure-posting/ Share on other sites More sharing options...
evanct Posted August 12, 2009 Author Share Posted August 12, 2009 oh that was careless of me, I was removing the parent post from the array, not the child post... needed to use unset($a[$post['post_id']]) in the $a2 loop Link to comment https://forums.phpfreaks.com/topic/169986-solved-tree-structure-posting/#findComment-896751 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.