I am having difficulty conceptualizing a recursive function to add responses to comments, responses to answers, answers to answers to answers, etc.
This is my comment table:

Which SHOULD look like the one shown when rendering:

At its core, I can display every comment related to article_id (with the exception of those NOT NULL, of course):
$comments = $commentClass->fetch_article_comments($article_id);
foreach($comments as $comment) {
$comment_id = $comment['comment_id'];
$member_id = $comment['member_id'];
$comment_text = $comment['comment_text'];
$comment_timestamp = timeAgo($comment['comment_timestamp']);
}
Now I assume that I need to add a recursive function at the end of the above statement foreach, but I still need to come up with something remotely successful, adding comment replies and answers to each answer.
- , , . . stackoverflow, -, , .
, , , php.
.
, , . , ?
php:
function display_comments($article_id, $parent_id=0, $level=0) {
global $comment;
global $member;
global $signed_in;
global $username;
$comments = $comment->fetch_article_comments($article_id, $parent_id);
foreach($comments as $data) {
$comment_id = $data['comment_id'];
$c_member_id = $data['member_id'];
$comment_text = $data['comment_text'];
$comment_timestamp = timeAgo($data['comment_timestamp']);
$member_data = $member->fetch_member_data($c_member_id);
$c_member_username = $member_data['member_username'];
$c_member_avatar = $member_data['member_avatar'];
$parent = $data['comment_parent'];
display_comments($article_id, $parent, $level+1);
}
}
PDO:
public function fetch_article_comments($article_id, $parent_id) {
if ($parent_id > 0) {
$parent_id = "= $parent_id";
} else {
$parent_id = "IS NULL";
}
$query = $this->db->prepare("SELECT * FROM `comments2` WHERE `article_id` = $article_id AND `comment_parent` $parent_id ORDER BY `comment_timestamp` DESC");
try{
$query->execute();
$comments = $query->fetchAll();
$query->closeCursor();
return $comments;
} catch(PDOException $e){
die($e->getMessage());
}
}