Converting numbers to visual rating (stars)? [clos

2020-02-25 11:43发布

问题:

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 7 years ago.

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.

回答1:

<?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



回答2:

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.



回答3:

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:

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.



回答5:

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 '+';