借助Luuk,硬限制一直有效,但分页仍然无法正常工作。
基于我的上一个问题,我目前正在为博客构建评论系统,并希望使其像Reddit一样。
我目前正在使用http://www.jongales.com/blog/2009/01/27/php-class-for-threaded-comments/的嵌套注释
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输出以及所有内容,但是问题是分页。每当我尝试通过偏移量限制进行分页时,都会打乱孩子的注释和结构,因为下一页没有原始父级来附加孩子等。
例如:
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();
该代码将限制父母和孩子的注释,但是我需要将其设置为仅限制父母,因此每页20个父母。
如果我在计数查询中设置,WHERE blog_post = 1 AND parent_id = 0
它将仅对父母计数,但是当$comments
查询中达到20个配额时,它将删除子注释。
寻找一种方式做到这一点真的很头疼。任何帮助表示赞赏。
如何将代码更改为仅打印2个父母的示例:
public function print_comments($count =2)
{
foreach ($this->parents as $c)
{
$this->print_parent($c);
$count--;
if($count == 0) exit;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句