PHP:快速线程评论问题

时间:2010-12-10 16:06:31

标签: php mysql codeigniter threaded-comments

我基本上试图编写一个简单的线程评论系统,用户可以在其中评论其他用户的评论。它只允许一个级别的评论。

数据库中的注释表类似于: - ID - 文字 - 时间戳 - parent_id(可以为NULL)

我的问题是如何查询评论及其子女(评论)?我只是不确定它们在阵列中的位置,然后如何正确地循环和输出它们。

非常感谢您的帮助=)

2 个答案:

答案 0 :(得分:2)

如果只有一个级别,你可以获得所有评论并将它们融入你想要的结构中。你可以这样做:

function get_comments()
{
    $sql = 'select * from comments order by timestamp';
    $result = $this->db->query($sql)->result();

    $comments = array();
    foreach ($result as $row)
    {
        if ($row->parent_id)
        {
            $comments[$row->parent_id]->children[] = $row;
        }
        else
        {
            $comments[$row->id] = $row;
            $comments[$row->id]->children = array();
        }
    }

    return array_values($comments);
}

答案 1 :(得分:1)

以下是关于如何处理此问题的相当详细的解释:

http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

相关问题