如何使用 php 进行简单的星级评分?

How to make simple star rating using php?

我想做一个星级显示。这是我的代码。

<?php $rate = 4; ?>

<i class="material-icons md-18">star</i>
<i class="material-icons md-18">star</i>
<i class="material-icons md-18">star</i>
<i class="material-icons md-18">star</i>
<i class="material-icons md-18">star_border</i>

我想做到:例如,如果 $rate = 3 显示 3x 星,2x star_border。 如果 $rate = 4 显示 4x star, 1x star_border

这是我的代码太长了。我想要更短更实用的。

<?php $rate = 1;?>
<?php if ($rate == 1): ?>
<i class="material-icons md-18">star</i>
<i class="material-icons md-18">star_border</i>
<i class="material-icons md-18">star_border</i>
<i class="material-icons md-18">star_border</i>
<i class="material-icons md-18">star_border</i>
<?php elseif ($rate == 2): ?>
<i class="material-icons md-18">star</i>
<i class="material-icons md-18">star</i>
<i class="material-icons md-18">star_border</i>
<i class="material-icons md-18">star_border</i>
<i class="material-icons md-18">star_border</i>
<?php elseif ($rate == 3): ?>
<i class="material-icons md-18">star</i>
<i class="material-icons md-18">star</i>
<i class="material-icons md-18">star</i>
<i class="material-icons md-18">star_border</i>
<i class="material-icons md-18">star_border</i>
<?php elseif ($rate == 4): ?>
<i class="material-icons md-18">star</i>
<i class="material-icons md-18">star</i>
<i class="material-icons md-18">star</i>
<i class="material-icons md-18">star</i>
<i class="material-icons md-18">star_border</i>
<?php elseif ($rate == 5): ?>
<i class="material-icons md-18">star</i>
<i class="material-icons md-18">star</i>
<i class="material-icons md-18">star</i>
<i class="material-icons md-18">star</i>
<i class="material-icons md-18">star</i>
<?php endif;?>

这应该对你有用。

<?php
$rate = 3;
for ($x = 0; $x < $rate; $x++) {
    echo '<i class="material-icons md-18">star</i>';
}
for ($x = 0; $x < 5-$rate; $x++) {
    echo '<i class="material-icons md-18">star_border</i>';
}
?>

您回应的开始次数与您的评分所显示的次数相同。然后根据需要回显星形边框。