php - 查询数据库中的分层数据结构并显示结果

标签 php mysql

我想在我的网站上使用 PHP-MySql 实现高级评论系统。为此,我最终选择了一个 3 级评论回复系统。 好吧,为此我遇到了this文章实现 SQL 数据库的数据结构。

我计划将 nested set mdoel 用于我想要使用的功能。评论的结构是这样的-

<ul>
    <li>Parent comment</li>
        <ul>
            <li>First reply of parent comment</li>
            <ul>
                <li>reply of the previous reply</li>
                   <ul>
                       <li>reply of the previous reply</li>
                       <li>another reply of the previous reply</li>
                   </ul>
                <li>another reply of the previous comment</li>
             </ul>
             <li>second reply of the parent comment</li>
        </ul>
</ul>

对于这种类型的结构,我一直在使用 PHP 来显示检测父项及其子项的查询唯一(用于获取与每个评论关联的用户详细信息)并在方式,如果如上所示。有没有人知道如何去做。请帮帮我。

编辑:

我在 SQL 中有一个单独的用户表作为 user.id=comment.id 链接到评论表。因此,考虑到这一点,检测每个评论的用户事件的推荐方法是什么?我的意思是,对于前者,我想为父评论 2 的子评论获取用户名和电子邮件。这怎么可能完成?

最佳答案

使用“查找节点的深度”中的查询,此 PHP 代码将创建嵌套列表。

$cur_depth = -1;
while ($row = mysqli_fetch_assoc($query)) { // Loop through results of query
  if ($row['depth'] > $cur_depth) {
    echo "<ul>\n";
    $cur_depth = $row['depth'];
  }
  else while ($cur_depth > $row['depth']) {
    echo "</ul>\n";
    $cur_depth--;
  }
  echo "<li>" . $row['comment'] . "</li>\n";
}
while ($cur_depth > -1) {
  echo "</ul>\n";
  $cur_depth--;
}

关于php - 查询数据库中的分层数据结构并显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12028633/

相关文章:

php - 如何制作现场宏?

php - 如何从mysql获取替代记录?

php - 在我的 vps 上将 mysql 5.1 升级到 5.5 安全吗?

Javascript 显示在错误日志中

php - 如何优化 PHP 中巨大列表的存储和获取?

php - 查询带数据昼夜sql

c# - 是否可以将 PHP Regex(使用子例程调用)转换为 C# regex?

php - 无法使用 PHP 脚本远程连接到 MySQL 错误 (13),通过 CLI 连接有效

php - 如何使用 while 循环将 4 个项目排成一行?

mysql - 使用 Prometheus + Grafana 监控 mysql 表增长