我正在尝试像Disqus那样制作一个评论线程。我在 PHP 中设置逻辑以显示注释时遇到问题,以便可以回复每个注释,然后这些注释将保持相互关联。
这是我的 MySQL 注释表:
comment_id comment item_id replied_to_id time
1 hello1 1 1 1:00pm
2 hello2 1 1 2:00pm
3 hello3 1 3 3:00pm
4 hello4 2 4 4:00pm
5 hello5 1 2 2:00pm
6 hello6 1 3 6:00pm
item_id
是指示注释正在讨论的父项的列。
如果我从数据库中提取所有带有 item_id=1
的评论,那么我不确定如何对它们进行线程处理,以使 comment_id
和 replied_to_id
正确匹配。例如,comment_id=2
应与comment_id=1
匹配。
这是我的PHP:
<?foreach($comments as $row){
if($row->comment_id==$row->replied_to_id){
echo $row->comment."-".$row->time; //desired output: hello1-1:00pm
foreach($comments as $sub_row){
if($row->comment_id!=$sub_row->replied_to_id){
echo $sub_row->comment."-".$sub_row->time;// desired output: hello2-2:00pm
foreach($comments as $sub_sub_row){
if($row->comment_id!=$sub_sub_row->replied_to_id){
echo $sub_sub_row->comment."-".$sub_sub_row->time;// desired output: hello5-5:00pm
}
}
}
}
}
else{
echo $row->comment."-".$row->time; // desired output: hello3-3:00pm
}
}
这看起来不对劲。必须有更好的方法来做到这一点。
简单的演示,不一定是最佳的,但可以工作:
function displayComments(array $comments, $parentId = null) {
foreach ($comments as $comment) {
if ($comment['replied_to_id'] == $parentId) {
echo $comment['comment'];
displayComments($comments, $comment['id']);
}
}
}
这假设顶级注释没有replied_to_id
( null
)。您的评论1
回复1
的示例没有多大意义。