评论与回复php代码,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 | 1 | 2 |
我寫的這段代碼只是為了顯示評論,但我希望評論能夠顯示評論的回復(如果有的話).在它顯示下一個評論之前
$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'].'';
echo 'State Name: '.$detail['byy'].'';
echo 'City Name: '.$detail['name'].'';
echo '';
}
}
?>
解決方法:
以下是以下偽代碼的實際代碼:
// 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 = '
- ';
foreach( $all_comments as $comment ) {
$comments .= '
'.$comment->user_comment.'
by: '.$comment->byy.'
';// print replies
$comments .= print_comments( $topic_id, $comment->comment_id ); // recursive
$comments .= '
';}
$comments .= '
';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
foreach( $all_comments as $comment ) {
$comment->user_comment
by: $comment->byy
// print replies
print_comments( $topic_id, $comment->comment_id ); // recursive
}
}
優點:更易于理解和實施.
缺點:使用大量查詢.
任何其他方式來克服利弊?
請記住,當與分頁一起使用時,這種做法很難實現.
>使用單個查詢獲取所有評論和回復
>將所有這些格式化為comment =>回復關系
>循環關系并顯示它
標簽:php,mysql,yii2
來源: https://codeday.me/bug/20190627/1309900.html
總結
以上是生活随笔為你收集整理的评论与回复php代码,php – 显示评论和回复?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: kattle的java安装,Kettle
- 下一篇: php mail 失败,php-mail