My SQL table structure:
id | comment | thread_id | parent_id |
---|---|---|---|
1 | comment1 | 1 | null |
2 | comment2 | 1 | 1 |
3 | comment3 | 1 | 2 |
Use Below code for create tree array:
function getCommentHierachy($threadId, $comments) { $rtnVal = array(); foreach ($comments as $comment) { if ($threadId == $comment['thread_id']) { $rtnVal$comment['id']] = array('comment_data'=>$comment, 'parent_id' => $comment['parent_id'], "id" => $comment['id'], 'childs'=>array()); } } $rtnVal = parseTree($rtnVal); return $rtnVal; } function parseTree($tree, $root = null) { $return = array(); # Traverse the tree and search for direct children of the root foreach($tree as $child => $parent) { # A direct child is found if($parent['parent_id'] == $root) { # Remove item from tree (we don't need to traverse this again) unset($tree[$child]); # Append the child into result array and parse its children $return[] = array( 'id' => $child, 'comment_data'=>$parent['comment_data'], 'children' => parseTree($tree, $child) ); } } return empty($return) ? null : $return; }
Use below code to print tree commenting:
function printTree($viewer,$topicId,$threadId,$title,$tree,$count=0) { if(!is_null($tree) && count($tree) > 0) { if($count==0){ echo '<ul id="nestedlist" class="nestedlist">'; }else{ echo '<ul>'; } foreach($tree as $node) { echo '<li style="font-size:15px;">'.$node['comment_data']['profile_pic'].'<span style="margin:10px;"><a href="/profile/'.$node['comment_data']['username'].'" ><b style="color:black;font-size:14px;">'.ucfirst($node['comment_data']['displayname']).'</b></a> wrote at '.$node['comment_data']['modified_date'].':</span><br/>'; echo '<div style="padding-left: 26px;"><p>'.$node['comment_data']['body'].'</p>'; echo '<span style="margin-left: 10px;font-size:15px;font-weight:bold;"><a href="/forums/topic/'.$topicId.'/nestedreply/post-create?parent_id='.$node['comment_data']['id'].'&thread_id='.$threadId.'">Reply</a>'; echo '</div>'; printTree($viewer,$topicId,$threadId,$title,$node['children'],1); echo '</li>'; } echo '</ul>'; } }
The post Hierarchical Tree Commenting using MySQL PHP appeared first on Techathon.