亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

平均非整數時如何顯示半星(星級)

平均非整數時如何顯示半星(星級)

PHP
拉風的咖菲貓 2023-08-26 17:45:36
我使用此代碼來顯示帶有半滿星的平均評分(如果平均評分不是整數)。效果很好。<?php$stars   = '';for ( $i = 1; $i <= $avrating + 1; $i++ ) {$width = intval( $i - $avrating > 0 ? 20 - ( ( $i - $avrating ) * 20 ) : 20 );if ( 0 === $width ) {    continue;}    if($avrating < 5){        $stars .= '<span style="overflow:hidden; width:' . $width . 'px" class="dashicons dashicons-star-filled"></span>';        if ( $i - $avrating > 0 ) {            $stars .= '<span style="overflow:hidden; position:relative; left:-' . $width .'px;" class="dashicons dashicons-star-empty"></span>';         }    }}if($avrating >= 5){    for ($i = 1; $i <= 5; $i++) {        echo '<span style="overflow:hidden;" class="dashicons dashicons-star-filled"></span>';    }  }  echo $stars;?> 但是,在這種情況下,并非所有星星都會顯示。例如,如果評分為3.5,則顯示4顆星,第四顆星為半滿。這是圖像:1 : https://i.stack.imgur.com/2aoGx.png但我需要顯示所有五顆星:最后一個空的四分之一是半填充的(例如,如果評級為 3.5)并且前三個已滿。我可以把所有的星星都拿出來。有了這個代碼:<?php$stars = '';for ( $i = 1; $i <= 5 ; $i ++ ) {    if ( $i <= $avrating ) {        $stars .= '<span class="dashicons dashicons-star-filled"></span>';    } else {        $stars .= '<span class="dashicons dashicons-star-empty"></span>';    }}                                   echo   $stars;?>  但結果,我自然達不到這個結果。這是我得到的:你看,第四顆星里沒有一半。我認為可以將這兩個代碼片段結合起來,但我的知識還不夠,如何做到這一點?;蛘咭苍S這根本不可能。請幫助解決這個問題。
查看完整描述

2 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

我將創建一個簡單的函數,它根據給定的評級返回給定星星的填充水平:


<?php

function getStarClass(int $starPosition, float $rating): string

{

  if ($starPosition <= $rating) {

    return 'filled';

  }

  if ($starPosition - $rating < 1) {

    return 'half-filled';

  }

  return 'empty';

}


$avrating = 3.5;

?>


<?php for ($star = 1; $star <= 5; $star++): ?>

  <span class="dashicons dashicons-star-<?= getStarClass($star, $avrating) ?>"></span>

<?php endfor ?>

請注意,我還使用 PHP 的替代語法來顯示 HTML,因為我相信它更適合該目的,但這完全是可選的。


查看完整回答
反對 回復 2023-08-26
?
Qyouu

TA貢獻1786條經驗 獲得超11個贊

您可以添加一個額外的子句,檢查循環是否大于評級但小于下一個評級作為半啟動評級...


$stars = '';

for ( $i = 1; $i <= 5 ; $i ++ ) {

    if ( $i <= $avrating ) {

        $stars .= '<span class="dashicons dashicons-star-filled"></span>';

    } elseif ( $i < $avrating + 1 && $i > $avrating ) {

        $stars .= '<span class="dashicons dashicons-star-half"></span>';

    } else {

        $stars .= '<span class="dashicons dashicons-star-empty"></span>';

    }

}  

您還可以通過將其作為部件添加來減少大量重復的樣板 HTML...


$stars = '';

for ( $i = 1; $i <= 5 ; $i ++ ) {

    $stars .= '<span class="dashicons dashicons-star-';

    if ( $i <= $avrating ) {

        $stars .= 'full';

    } elseif ( $i < $avrating + 1 && $i > $avrating ) {

        $stars .= 'half';

    } else {

        $stars .= 'empty';

    }

    $stars .= '"></span>';

}  


查看完整回答
反對 回復 2023-08-26
  • 2 回答
  • 0 關注
  • 167 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號