I created an example (for me) of how I must get the comments and replies from the database.
Here is the result for example:
//I am ONLY thinking a query like this
$q = "SELECT * FROM comments_table WHERE post = 'url_code' ORDER BY date DESC";
//An example result (Not used the query above)
$comment = array(
array(
'id' => '7',
'user' => 'Jul',
'post_id' => '1',
'comment_id' => '7',
'reply_id' => '1',
'date' => 'Jul 2016',
'message' => 'hello7'
),
array(
'id' => '6',
'user' => 'Jun',
'post_id' => '1',
'comment_id' => '6',
'reply_id' => '1',
'date' => 'Jun 2016',
'message' => 'hello6'
),
array(
'id' => '5',
'user' => 'May',
'post_id' => '1',
'comment_id' => '5',
'reply_id' => '3',
'date' => 'May 2016',
'message' => 'hello5'
),
array(
'id' => '4',
'user' => 'Apr',
'post_id' => '1',
'comment_id' => '4',
'reply_id' => '2',
'date' => 'Apr 2016',
'message' => 'hello4'
),
array(
'id' => '3',
'user' => 'Mar',
'post_id' => '1',
'comment_id' => '3',
'reply_id' => '',
'date' => 'Mar 2016',
'message' => 'hello3'
),
array(
'id' => '2',
'user' => 'Feb',
'post_id' => '1',
'comment_id' => '2',
'reply_id' => '',
'date' => 'Feb 2016',
'message' => 'hello2'
),
array(
'id' => '1',
'user' => 'Jan',
'post_id' => '1',
'comment_id' => '1',
'reply_id' => '',
'date' => 'Jan 2016',
'message' => 'hello'
)
);
Then the code to output it in the page:
foreach ($comment as $key => $value) {
if(empty($value['reply_id'])) {
$comments[$value['comment_id']] = array('user' => $value['user'], 'message' => $value['message']);
} else {
$replies[] = array('id' => $value['id'], 'reply_id' => $value['reply_id'], 'user' => $value['user'], 'message' => $value['message']);
}
}
$reply_count = count($replies);
for ($i=0; $i < $reply_count; $i++) {
$reply_id = $replies[$i]['reply_id'];
if(isset($comments[$reply_id])) {
$cc[$reply_id]['comment'] = array('user' => $comments[$reply_id]['user'], 'message' => $comments[$reply_id]['message']);
$cc[$reply_id][$replies[$i]['id']] = array('user' => $replies[$i]['user'], 'message' => $replies[$i]['message']);
}
}
foreach ($cc as $kkk => $vvv) {
$reply = '';
foreach ($vvv as $kk => $vv) {
if(is_int($kk)) {
$reply .= $vv['user'] . ' reply: ' . $vv['message'] . '<br>';
} else {
$comment = $vv['user'] . ' comment: ' . $vv['message'] . '<br>';
}
}
echo $comment . $reply . '<br>';
}
The results are okay, but my question is, is this code okay to use?