php 将数字转换为视觉评级(星级)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10250825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting numbers to visual rating (stars)?
提问by salim basar
in my database ? have numbers 1, 2, 2.5, 3, 3.5, 4, 4.5and 5
在我的数据库中?有数字1, 2, 2.5, 3, 3.5, 4,4.5和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.
我在数据库上有评级标签。
回答by Wouter Rutgers
<?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
*假设您使用的是 PHP
回答by dqhendricks
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
当我过去这样做时,我在一张 5 颗填充星星的图像下方使用了一张 5 颗空星星的图像。然后我做了类似的事情
filled-stars.width = (empty-stars.width * (rating / 5)
This way you can display ratings of like 3.2978 etc.
通过这种方式,您可以显示 3.2978 等的评级。
回答by hakre
You can do that with PHP, HTML and CSS:
你可以用 PHP、HTML 和 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.
然后您可以使用 CSS 设置样式,以便根据星星显示背景图像。如果您将<b>标签转换为标签,<a>它可能更具语义。
回答by hakre
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.
结合一点点 Javascript,您可以实现功能齐全的 ratings 小部件。
回答by Sampo Sarrala - codidact.org
Here, this adds stars echo '*';and halfs if needed echo '+';
Change '*'and '+'for example to <img src="star.gif" />and <img src="halfstar.gif" />
在这里,echo '*';如果需要,这会增加星星和一半的echo '+';
变化'*','+'例如到<img src="star.gif" />和<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 '+';

