为了账号安全,请及时绑定邮箱和手机立即绑定

平均非整数时如何显示半星(星级)

平均非整数时如何显示半星(星级)

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;?>  但结果,我自然达不到这个结果。这是我得到的:你看,第四颗星里没有一半。我认为可以将这两个代码片段结合起来,但我的知识还不够,如何做到这一点。或者也许这根本不可能。请帮助解决这个问题。
查看完整描述

2 回答

?
弑天下

TA贡献1818条经验 获得超7个赞

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


<?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 关注
  • 94 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信