遍历所有线程注释级别

时间:2014-03-10 17:55:58

标签: php foreach comments

我正在为我的网站制作评论系统。我希望它有一个线程评论系统,我试图找出循环不同级别线程的最佳方法。我真的不认为嵌套foreach循环是最好的方法,但我似乎无法想到任何其他方式。这是我的嵌套循环代码(我知道,我还处于开发阶段):

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;
}

如果您需要更多信息,请告诉我并感谢您的帮助!

编辑:

您可以在此处查看完整的课程:http://pastebin.com/ukRMJcA6

1 个答案:

答案 0 :(得分:1)

递归函数/方法将是您的解决方案。

<强> Understanding recursion

<强> What is a RECURSIVE Function in PHP?