Converting numbers to visual rating (stars)? [clos

2020-02-25 10:46发布

in my database ı have numbers 1, 2, 2.5, 3, 3.5, 4, 4.5 and 5

I want to convert these numbers to stars.

I have a full star and a half star.

How ı can do that after getting information from database?

I have the rating tag on the database.

5条回答
放荡不羁爱自由
2楼-- · 2020-02-25 11:30
<?php
    for($x=1;$x<=$starNumber;$x++) {
        echo '<img src="path/to/star.png" />';
    }
    if (strpos($starNumber,'.')) {
        echo '<img src="path/to/half/star.png" />';
        $x++;
    }
    while ($x<=5) {
        echo '<img src="path/to/blank/star.png" />';
        $x++;
    }
?>

*Assuming you are using PHP

查看更多
叛逆
3楼-- · 2020-02-25 11:47

You can do that with PHP, HTML and CSS:

<div class="star-<?=$number?>">
    <b></b><b></b><b></b><b></b><b></b>
</div>

You can then style that with CSS, so to display background images according to stars. If you convert the <b> tags to <a> tags it's probably more semantic.

查看更多
4楼-- · 2020-02-25 11:50

Here, this adds stars echo '*'; and halfs if needed echo '+';
Change '*' and '+' for example to <img src="star.gif" /> and <img src="halfstar.gif" />

// This number of stars:
$number = 2.7;

// Make it integer:
$stars = round( $number * 2, 0, PHP_ROUND_HALF_UP);

// Add full stars:
$i = 1;
while ($i <= $stars - 1) {
    echo '*';
    $i += 2;
}
// Add half star if needed:
if ( $stars & 1 ) echo '+';
查看更多
迷人小祖宗
5楼-- · 2020-02-25 11:52

When I have done this in the past, I used one image of 5 empty stars underneath one image of 5 filled stars. I then did something like

filled-stars.width = (empty-stars.width * (rating / 5)

This way you can display ratings of like 3.2978 etc.

查看更多
干净又极端
6楼-- · 2020-02-25 11:52

Consider using sprites. Start with a graphic that contains a row of stars for each possible rating, and then compute the background offset by multiplying the height of each half-star graphic times the number of half-stars in the rating.

E.g.:

<?php
$offset =
    ($rating / .5)  // number of half-stars in $rating
  * 15;             // height of each sprite in stars.png
?>
<div style="background-image:url("stars.png");background-position:0 <?php echo $offset; ?>px;"></div>

Combined with a little bit of Javascript, you can implement a fully-featured ratings widget.

查看更多
登录 后发表回答