【发布时间】:2021-03-04 15:37:39
【问题描述】:
由于 Luuk,硬限制有效,但分页仍然无效。
基于我之前的问题,我目前正在为一个博客构建 cmets 系统,并希望使它像 reddit 一样。
我目前正在使用 http://www.jongales.com/blog/2009/01/27/php-class-for-threaded-comments/ 的嵌套 cmets
class Threaded_comments
{
public $parents = array();
public $children = array();
/**
* @param array $comments
*/
function __construct($comments)
{
foreach ($comments as $comment)
{
if ($comment['parent_id'] === NULL)
{
$this->parents[$comment['id']][] = $comment;
}
else
{
$this->children[$comment['parent_id']][] = $comment;
}
}
}
/**
* @param array $comment
* @param int $depth
*/
private function format_comment($comment, $depth)
{
for ($depth; $depth > 0; $depth--)
{
echo "\t";
}
echo $comment['text'];
echo "\n";
}
/**
* @param array $comment
* @param int $depth
*/
private function print_parent($comment, $depth = 0)
{
foreach ($comment as $c)
{
$this->format_comment($c, $depth);
if (isset($this->children[$c['id']]))
{
$this->print_parent($this->children[$c['id']], $depth + 1);
}
}
}
public function print_comments()
{
foreach ($this->parents as $c)
{
$this->print_parent($c);
}
}
}
这是以数组形式提供的数据的示例用法。请记住,如果您的数据是其他格式,则必须修改类。
$comments = array( array('id'=>1, 'parent_id'=>NULL, 'text'=>'Parent'),
array('id'=>2, 'parent_id'=>1, 'text'=>'Child'),
array('id'=>3, 'parent_id'=>2, 'text'=>'Child Third level'),
array('id'=>4, 'parent_id'=>NULL, 'text'=>'Second Parent'),
array('id'=>5, 'parent_id'=>4, 'text'=>'Second Child')
);
$threaded_comments = new Threaded_comments($comments);
$threaded_comments->print_comments();
示例输出:
Parent
Child
Child Third level
Second Parent
Second Child
我已经设置了深度限制,创建了 html 输出和所有内容,但问题是分页。每当我尝试通过偏移限制进行分页时,它会破坏子 cmets 和结构,因为下一页没有原始父级在哪里附加子级等。
例如:
select count(*) as found_comments from comments where blog_post = 1 and parent_id is null;
result = 20; // lets say its 20 parent comments limit from query above.
$query = "select * from comments where blog_post = 1 LIMIT 0,20";
$comments = [];
foreach ($query as $row)
{
$comments[] = [
'id' => $row['id'],
'parent_id' => $row['parent_id'],
'text' = $row['text'],
'added' => $row['added']];
}
$threaded_comments = new Threaded_comments($comments);
$threaded_comments->print_comments();
此代码将限制父和子 cmets,但我需要将其设置为仅限制父母,因此每页 20 个父母。
如果我在计数查询中设置WHERE blog_post = 1 AND parent_id = 0
它只会计算父母,但会在 $comments 查询中达到 20 个配额时删除子 cmets。
找到一种方法来做到这一点真的很头疼。任何帮助表示赞赏。
【问题讨论】: