层次结构评论系统php
发布时间:2020-12-13 13:42:49 所属栏目:PHP教程 来源:网络整理
导读:我想做铁饼/ reddit /喜欢评论系统,我的评论数据库中有一个“id_answer”(由defaut设置为0)字段,当用户回答另一个评论时,该字段是父评论的“id”. 我有一个数组中的线程的注释,但我不知道如何过滤每个循环过滤器得到这样的东西: comment lvl 1 ($array[id_a
我想做铁饼/ reddit /喜欢评论系统,我的评论数据库中有一个“id_answer”(由defaut设置为0)字段,当用户回答另一个评论时,该字段是父评论的“id”.
我有一个数组中的线程的注释,但我不知道如何过滤每个循环过滤器得到这样的东西:
在数据库中使用三个字段;
>“id”,每个评论都是唯一的 假设您要显示ID为“123”的新闻文章的评论树 从mysql中选择时,使用此thread_id选择所有内容: SELECT id,parent FROM comments WHERE thread_id = 123 然后你应该预先解析你的数组,让孩子给他们的父母评论,并使用递归显示来显示每个评论及其子列表. 举个例子: // getting the comments from mysql,I'm obviously not bothering // to check the return value,but in your code you should do it $result = mysqli_query("SELECT id,parent FROM comments WHERE thread_id = 123"); $comments = array(); while ($row = mysqli_fetch_array($result)) { $row['childs'] = array(); $comments[$row['id']] = $row; } // This is the array you get after your mysql query // Order is non important,I put the parents first here simply to make it clearer. /* $comments = array( // some top level (parent == 0) 1 => array('id' => 1,'parent' => 0,'childs' => array()),5 => array('id' => 5,2 => array('id' => 2,10 => array('id' => 10,// and some childs 3 => array('id' => 3,'parent' => 1,6 => array('id' => 6,'parent' => 2,4 => array('id' => 4,7 => array('id' => 7,'parent' => 3,8 => array('id' => 8,'parent' => 7,9 => array('id' => 9,'parent' => 6,); */ // now loop your comments list,and everytime you find a child,push it // into its parent foreach ($comments as $k => &$v) { if ($v['parent'] != 0) { $comments[$v['parent']]['childs'][] =& $v; } } unset($v); // delete the childs comments from the top level foreach ($comments as $k => $v) { if ($v['parent'] != 0) { unset($comments[$k]); } } // now we display the comments list,this is a basic recursive function function display_comments(array $comments,$level = 0) { foreach ($comments as $info) { echo str_repeat('-',$level + 1).' comment '.$info['id']."n"; if (!empty($info['childs'])) { display_comments($info['childs'],$level + 1); } } } display_comments($comments); 这给出了以下结果: - comment 1 -- comment 3 --- comment 7 ---- comment 8 - comment 5 - comment 2 -- comment 6 --- comment 9 -- comment 4 - comment 10 我把ORDER BY等等留给你,因为它不应该造成任何问题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |