我正在尝试建立评论和答复系统,但是我遇到了一些问题。我想用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>";
}
答案 0 :(得分:2)
每次处理新评论时,您都需要重置$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>";
对于该部分代码更有意义。