PHP 带有比较运算符和小数位的脚本逻辑

PHP script logic with comparison operators and decimal place

我正在开发 Web 应用程序并做出(可能是愚蠢的)决定尝试建立评级系统而不是实施其他人的。

下面是网络应用程序的屏幕截图。十进制值是从数据库中检索的值。我正在使用以下逻辑将值转换为星形表示。

for($x=1;$x<=$this->retreat->total_review_activities_rating;$x++) {
   echo '<i class="fas fa-star"></i>';
}
if (strpos($this->retreat->total_review_activities_rating,'.')) {
   echo '<i class="fas fa-star-half-alt"></i>';
   $x++;
}
while ($x<=5) {
   echo '<i class="far fa-star"></i>';
   $x++;
}

从屏幕截图中可以看出,值 5.000 正在循环中击中半星选项。如何调整第二个参数以避免这种情况发生?

感谢任何帮助。

您需要使用 strpos 更改条件,它始终为真。

例如比较AVG和整数。

if ($this->retreat->total_review_activities_rating != (int)$this->retreat->total_review_activities_rating) {
   // if (4.800 != 4) {true,  show half star}
   // if (5.000 != 5) {false, no half star}
   echo '<i class="fas fa-star-half-alt"></i>';
   $x++;
}

strpos()函数总是输出真,因为它输出的位置在布尔逻辑下不是0(假)。

除此之外,您的代码对于一个非常简单的问题来说似乎过于复杂,我会以不同的方式解决这个问题。 一定要用小数作为数值,然后用它来生成星数。 解析句点似乎很愚蠢。

while($x > 0) { //While there is still enough rating for a star left
    if($x >= 0.75) {
        //Add a full star
        echo '<i class="fas fa-star"></i>';
        $x--; //Remove one start rating
    else if($x < 0.25) {
        //Don't display a start
        $x--; //There isn't enough left for a star so we must be done.
    else {
        //Display a half-star
        echo '<i class="fas fa-star-half-alt"></i>';
        $x--; //There is only enough for a half start left so we must be done
    }
}

这一切都在一个循环中,不依赖于 "limit" 评级,并且使用的处理时间比您的解决方案少。 它甚至可以放在给定评分和返回星 html 的函数中。

$rating = $this->retreat->total_review_activities_rating;

满星数为评分的整数部分。

$full_stars = (int) $rating;
echo str_repeat('<i class="fas fa-star"></i>', $full_stars);

如果评分的小数部分超过您选择的某个值,您将显示半颗星。

$half_star = $rating - $full_stars > 0.2;        // 0.2 for example
echo $half_star ? '<i class="fas fa-star-half-alt"></i>' : '';

剩余的空星数是可能的符号总数 (5) 减去目前显示的符号数。 (布尔值 $half_star 将转换为 int 0 或 1。)

$empty_stars = 5 - ($full_stars + $half_star);
echo str_repeat('<i class="far fa-star"></i>', $empty_stars);