alexander7567
alexander7567

Reputation: 664

Loop through all threaded comments levels

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

Upvotes: 0

Views: 252

Answers (1)

Ricardo Barros
Ricardo Barros

Reputation: 205

Recursive function/method would be your solution.

Understanding recursion

What is a RECURSIVE Function in PHP?

Upvotes: 1

Related Questions