我有一个表comments,看起来像这样,添加了一些模型内容:
+------------+---------+----------+-------------------+------------------------------------+---------------------------+
| comment_id | user_id | movie_id | comment_parent_id | comment_content | comment_creation_datetime |
+------------+---------+----------+-------------------+------------------------------------+---------------------------+
| 26 | 1 | 16329 | 0 | Första | 2016-01-24 10:42:49 |
| 27 | 1 | 16329 | 26 | Svar till första | 2016-01-24 10:42:55 |
| 28 | 1 | 16329 | 26 | Andra svar till förta | 2016-01-24 10:43:06 |
| 29 | 1 | 16329 | 28 | Svar till "andra svar till första" | 2016-01-24 10:43:23 |
+------------+---------+----------+-------------------+------------------------------------+---------------------------+
Run Code Online (Sandbox Code Playgroud)
我试图显示评论Reddit样式,如下图:
我试图获取所有注释SELECT * FROM comments WHERE movie_id = :movie_id ORDER BY comment_creation_datetime DESC,然后递归回显它们.
我尝试了一堆foreach循环,但没有一个按预期工作
foreach($this->comments as $value){ ?>
<div class="comment">
Comment content <?php echo $value->comment_content; ?>
<?php if($value->comment_parent_id > 0){
foreach($value as $sub_comment){ ?>
<div class="comment">
comment comment on comment: <?php echo $value->comment_content; ?>
</div>
<?php }} ?>
</div>
<?php }
Run Code Online (Sandbox Code Playgroud)
如何使用foreach循环以嵌套的Reddit样式回显注释?
我会使用一些递归函数,你从那些parent_id == 0,并递归打印所有作为其直接子代的函数。
这段代码没有经过测试,但你可以得到这个想法:
function printComment($comment, $comments)
{
foreach($comments as $c)
{
if($c->parent_id == $comment->comment_id)
{
$output .= "<li>".printCommment($c)."</li>";
}
}
$output = "<ul>".$comment->comment_content."</ul>".$output;
return $output;
}
foreach($this->comments as $comment)
{
if($comment->parent_id == 0)
{
echo printComment($comment,$this->comments);
}
}
Run Code Online (Sandbox Code Playgroud)