【问题标题】:How to display half star when average non-integer (Star rating)平均非整数时如何显示半星(星级)
【发布时间】:2026-02-22 18:05:01
【问题描述】:

我使用此代码显示带有半满星的平均评分(如果平均评分不是整数)。效果很好。

<?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 颗星,第四颗为半满。这是图像:1https://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;
?>  

但结果,我自然达不到结果。这是我得到的:

你看,第四颗星没有一半。我认为可以将这两个代码片段结合起来,但是我的知识还不够。或者这根本不可能。请帮忙解决这个问题。

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    我会做一个简单的函数,它会根据给定的评级返回给定星星的填充水平:

    <?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,因为我相信它更适合此目的,但这完全是可选的。

    【讨论】:

      【解决方案2】:

      您可以添加一个额外的子句来检查循环是否大于评级但小于下一个评级作为半开始评级...

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

      【讨论】: