簡體   English   中英

平均評分系統的邏輯不起作用

[英]Logic of average rating system not working

我正在嘗試計算1-5個人的平均評分。 我試圖通過將注釋總數保存到變量$no_of_comments = get_comments_number( $post_id );來做到這一點$no_of_comments = get_comments_number( $post_id ); 比我在for循環中計算總評分

for ($i=get_comments_number(0); $i <= $no_of_comments; $i++) { 
    $tot_stars +=  get_comment_meta( get_comment_ID(), 'rating', true );
}

然后計算平均評分$avg_rating = ($tot_stars / $no_of_comments); 最后,我開始展示我的評分

echo '<p id="avg-contain">';
            for ( $i = 1; $i <= 5; $i++ ) {
                if ( $i <= $avg_rating ) {
                    echo '<img src="' . plugins_url( 'images/icon.png' ) . '" />';
                } else {
                    echo '<img src="' . plugins_url( 'images/grey.png' ). '" />';
                }
            }
echo '</p>';

我不確定為什么會產生所有灰星,我已經使用相同的echo邏輯設置了單獨的等級,因此在上面的PHP中一定是邏輯錯誤。 也許$avg_rating不是整數?

您的注釋循環使用了看似錯誤的邏輯。 您只是從get_comments_number( 0 )迭代到$no_of_comments ,但是實際上並沒有在任何地方得到您的個人評論。

改為這樣做:

$args = array(
    'ID' => $post_id,
    'status' => 'approve',
);
$comments = get_comments( $args );
foreach( $comments as $comment ) { 
    $tot_stars +=  get_comment_meta( $comment->comment_ID, 'rating', true );
}

參考文獻

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM