Nested comments in PHP & MySQL

后端 未结 2 462
误落风尘
误落风尘 2020-12-09 00:02

I searched through the forums but couldn\'t get an authoritative answer. I want to implement a nested comment structure in a way like this:

    &l
2条回答
  •  攒了一身酷
    2020-12-09 00:58

    I had done something similar for my blogpost. Yet, I just tried out with the same data. When you say nested comments it is better you can use nested functions this way:

    function getComments($parent)
    {
        # Get the data from SQL.
        # Check if it has nested comments.
        if (hasComments())
            getComments($child); # $child is the ID of the current comment.
    }
    

    To make it this way, I have imported your data to MySQL and tried this:

    \n";
                while (($dat = mysql_fetch_array($res)) !== false)
                    echo "
  • ", $dat["text"], getComments($dat["id"]), "
  • \n"; echo "
\n"; } else echo ($parent === 0) ? 'No Comments!' : ""; } getComments(0); ?>

As I said before I have used nested functions, and as you asked the output is almost same (without the braces) this way:

  • This is the parent first comment!
    • This is the reply for the first parent comment!
      • This is a reply for the first reply of the parent comment!
      • This is a third reply for the first parent comment!
    • This is another reply for first parent comment!
  • This is gonna be parent second comment!
    • This is a reply for the second comment!
  • This is fourth parent comment!

Hope this helps out.

提交回复
热议问题