0

I am working on making a comment system for my website. I want it to have a threaded comment system and I am trying to figure out the best way to loop through different level threads. I really dont think having nested foreach loops is the best approach, but I cannot seem to think of any other way. Here is my code with the nested loops (Its sloppy i know, I am still in the development stages):

function display_comments($blog_post_id, $limit = 0) {
    global $dbh, $user;
    $return = "";
    $comments = $this->get_post_comments($blog_post_id);
    foreach ($comments as $comment) {
        $comment_user = $user->get_userdata($comment['comment_userid']);
        $return .= '<div class="media">
  <a class="pull-left" href="#">
    <img class="media-object" src="holder.js/64x64" alt="">
  </a>
  <div class="media-body">
    <h4 class="media-heading">'.$comment_user['username'].'</h4>
    '.$comment['comment_text'];
        $replies = $this->get_comment_replies($comment['comment_id']);
        foreach ($replies as $reply) {
            $comment_user = $user->get_userdata($comment['comment_userid']);
            $return .= '<div class="media">
  <a class="pull-left" href="#">
    <img class="media-object" src="holder.js/64x64" alt="">
  </a>
  <div class="media-body">
    <h4 class="media-heading">'.$comment_user['username'].'</h4>
    '.$comment['comment_text'];
            if ($this->reply_count($reply['comment_id'])) {
                $replies_level_1 = $this->get_comment_replies($reply['comment_id']);
                foreach ($replies_level_1 as $reply_level_1) {
                    $comment_user = $user->get_userdata($comment['comment_userid']);
                    $return .= '<div class="media">
  <a class="pull-left" href="#">
    <img class="media-object" src="holder.js/64x64" alt="">
  </a>
  <div class="media-body">
    <h4 class="media-heading">'.$comment_user['username'].'</h4>
    '.$reply_level_1['comment_text'];
                }
                $return .= '</div></div>';
            }
        }
        $return .= '</div></div>';
    }
    return $return;
}

Let me know if you need anymore info and thanks for your help!

EDIT:

You can see the entire class here of you need to: http://pastebin.com/ukRMJcA6

alexander7567
  • 665
  • 13
  • 35
  • 1
    Why dont you join the tables and get everything in one query and limit it. IF you want, use a flag for multi-threaded comments. Do ajaxed pagination. – Abhishek Saha Mar 10 '14 at 18:00

1 Answers1

1

Recursive function/method would be your solution.

Understanding recursion

What is a RECURSIVE Function in PHP?

Community
  • 1
  • 1
Ricardo Barros
  • 205
  • 1
  • 8