Jump to content

[SOLVED] tree structure posting


evanct

Recommended Posts

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.