加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 显示评论和回复?

发布时间:2020-12-13 17:01:28 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试显示评论和回复,但我真的不知道该怎么做.这是我的桌子. comment_id | byy | user_comment | topic_id | parent_id | 1 |obi |comment 1 | 1 | 0 | 2 |chima |comment 2 | 1 | 0 | 3 |eze |comment 1 reply | 1 | 1 | 4 |david |comment 2 reply |
我正在尝试显示评论和回复,但我真的不知道该怎么做.这是我的桌子.

comment_id | byy  | user_comment   | topic_id    | parent_id | 
   1       |obi   |comment 1       |    1        |    0      |
   2       |chima |comment 2       |    1        |    0      |
   3       |eze   |comment 1 reply |    1        |    1      |
   4       |david |comment 2 reply |    1        |    2      |

我写的这段代码只是为了显示评论,但我希望评论能够显示评论的回复(如果有的话).在它显示下一个评论之前

<?php
  $querycomment = comment::find()->where(['topic_id'=> Yii::$app->getRequest()->getQueryParam('id')])->all();

  foreach ($querycomment as $detail) {
    if($detail['parent_id']==0) {
      echo 'Country Name: '.$detail['user_comment'].'</br>';
      echo 'State Name: '.$detail['byy'].'</br>';
      echo 'City Name: '.$detail['name'].'</br>';
      echo '</br>';
    }
  }
?>

解决方法

以下是以下伪代码的实际代码:

<?php 
// print comments and/or replies body
function print_comments( $topic_id,$parent_id ) {
   $all_comments = Comment::find()
               ->where(
                   'topic_id' => $topic_id,'parent_id' => $parent_id
               )->all();

    if( empty($all_comment) ) {
      return "";
    }

    $comments = '<ul>';
    foreach( $all_comments as $comment ) {
        $comments .= '<li>
            <p> '.$comment->user_comment.' </p>
            <p> by: '.$comment->byy.' </p>';

            // print replies
            $comments .= print_comments( $topic_id,$comment->comment_id ); // recursive

        $comments .= '</li>';
    }
    $comments .= '</ul>';

    return $comments;
}
?>

将上面的代码放在视图文件的顶部.现在使用以下行显示/回显您的评论和回复.

<?php echo print_comments( Yii::$app->getRequest()->getQueryParam('id'),0); ?>

(上一个答案)

您可以尝试遵循此伪代码:

print_comments( queryParam(id),0); // parent_id = 0

// print comments and/or replies body
print_comments ( $topic_id,$parent_id ) {
   $all_comments = Comment::find()
               ->where(
                   topic_id => $topic_id,parent_id => $parent_id
               )->all();

    if( $all_comment count = zero )
      return

    <ul>
    foreach( $all_comments as $comment ) {
        <li>
            <p> $comment->user_comment </p>
            <p> by: $comment->byy </p>

            // print replies
            print_comments( $topic_id,$comment->comment_id ); // recursive

        </li>
    }
    </ul>
}

优点:更易于理解和实施.
缺点:使用大量查询.

任何其他方式来克服利弊?
请记住,当与分页一起使用时,这种做法很难实现.

>使用单个查询获取所有评论和回复>将所有这些格式化为comment =>回复关系>循环关系并显示它

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读