评论和回复系统



我正在尝试创建一个评论和回复系统,但我遇到了一些问题。我想用JSON打印评论和回复,如下所示:

{"comment":"data1","reply":[{"comment_id":"15","comment":"reply1"}]}

我已经这样做了,但回复在没有回复的评论中重复:

{"comment":"data1","reply":[{"comment_id":"15","comment":"reply1"}]}
{"comment":"data2","reply":[{"comment_id":"15","comment":"reply1"},{"comment_id":"14","comment":"reply2"}]}
{"comment":"Легко. data3 ","reply":[{"comment_id":"15","comment":"reply1"},{"comment_id":"14","comment":"reply2"},{"comment_id":"13","comment":"reply3"},{"comment_id":"13","comment":"reply4"}]}

例如,在回复中的第二条评论中,它显示了第一条评论的回复,但它不应该显示。

<?
$sql = "select * from comments where post_id=:post_id order by id desc";
$data = $db->prepare($sql);
$data->execute(array(':post_id' => $post_id));
$comments = $data->fetchAll();
$count = $data->rowCount();
foreach ($comments as $com) {
$sql = "select * from reply where post_id=? and comment_id=? order by id desc";
$data = $db->prepare($sql);
$data->execute([$com['post_id'], $com['id']]);
$replies = $data->fetchAll();
foreach ($replies as $reply) {
$xxx[] = [
'comment_id' => $reply['comment_id'],
'comment' => $reply['comment'],
];
$xyc = [
'comment' => $com['comment'],
'reply' => $xxx,
];
}
echo json_encode($xyc, JSON_UNESCAPED_UNICODE);
echo "<br></br>";
}

每次处理新注释时,都需要重置$xxx。否则,您只需继续添加,这就是为什么稍后的输出还包含来自早期评论的回复。

foreach ($comments as $com) {
$xxx = array();
//... etc

此外,为了使代码更有效率,您只需要运行

$xyc = [
'comment' => $com['comment'],
'reply' => $xxx,
];

一次,在foreach内部循环结束后。现在,它为每个回复运行一次,这是不必要的——你想等到所有回复都处理完毕,然后创建最终对象。

因此:

foreach ($replies as $reply) {
$xxx[] = [
'comment_id' => $reply['comment_id'],
'comment' => $reply['comment'],
];
}
$xyc = [
'comment' => $com['comment'],
'reply' => $xxx,
];
echo json_encode($xyc, JSON_UNESCAPED_UNICODE);
echo "<br></br>";

对代码的这一部分更有意义。

最新更新