由于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;
}
}