php - Comment and reply system

I am trying to make a comment and reply system but I'm facing some issues. I want to print comments and replies in JSON, like this:
{"comment":"data1","reply":[{"comment_id":"15","comment":"reply1"}]}
I have done this, but replies repeat in comments that do not have this reply:
{"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"}]}
For example in the second comment in replies it show the reply from the first comment, but it but it shouldn't show.
<?
$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>";
}
Answer
Solution:
You need to reset$xxx
every time you process a new comment. Otherwise you just keep on adding to it, which is why later output also contains replies from earlier comments.
foreach ($comments as $com) {
$xxx = array();
//... etc
Also, to make the code more efficient you only need to run
$xyc = [
'comment' => $com['comment'],
'reply' => $xxx,
];
once, after the inner foreach loop has ended. Right now it runs once for every reply, which is unnecessary - you want to wait till all the replies have been processed, and then create the final object.
So:
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>";
would make more sense for that section of the code.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the requested url was not found on this server. xampp
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.