How to display nested comments?

I have nested comments on my site and it gets longer and longer with replies.
I want to hide/Toggle replies, so I created a nested function which displays comments on parent_id recursively, and I will add ajax letter on.
I want to make it work with post_id call.

Here is the function :

$sql = "SELECT * FROM comments";
$stmt = $pdo->prepare($sql);
$MultiComments = array(
    'comments' => array(),
    'parent_comments' => array()
while ($row = $stmt->fetch()) {
    $MultiComments['comments'][$row['comment_id']] = $row;
    $MultiComments['parent_comments'][$row['comment_parent_id']][] = $row['comment_id'];
function listComments($parent, $comment){
    $html = "";
    if (isset($comment['parent_comments'][$parent])) {
        $html .= "<ul>\n";
        foreach ($comment['parent_comments'][$parent] as $comment_id) {
            if (!isset($comment['parent_comments'][$comment_id])) {
                $html .= "<li class='hasNoChild'>" . $comment['comments'][$comment_id]['comment'] . "</li>";
            } else {
                $html .= "<li class='HasChild'>" . $comment['comments'][$comment_id]['comment'];
                $html .= listComments($comment_id, $comment);
                $html .= "</li>";
        $html .= "</ul>\n";
    return $html;

And this is how I call it with parent id :

echo listComments(0,$MultiComments);

Thanks for helps

Can you explain a bit further on what you want it to do, what you’ve tried so far and what was wrong with your previous attempts?

I tried with where clause. but it displayed 2/10 comments, and I tried several diferent ways with creating new array and ofcourse couldnt get it work.

I want to dislay comments under posts recursively like a multi level menu. and add classes and style it.

I want to make it callable with postId instead of parent id : echo listComments(post-id-here,$MultiComments);

Thanks @droopsnoot

damn me, it worked with where clause, the problem was in function I was using commen_id instead of comment_parent_id.

Thanks again @droopsnoot

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.