【问题标题】:Convert rating to percentage in 5 star rating system在 5 星评级系统中将评级转换为百分比
【发布时间】:2015-06-21 11:49:41
【问题描述】:

我的一个项目采用 5 星评级系统。我想将每颗星转换为百分比值。

这是我的数据库

star1

star2

star3

star4

star5

tot_stars

average

我用来获得评分的计算

$cal = ($star1*1 + $star2*2 + $star3*3 + $star4*4 + $star5*5)/$total_stars;

$avg = number_format($cal, 2);

我想知道的是每颗星星的百分比是多少

示例:Yelp.com 在他们的网站上执行此操作

【问题讨论】:

  • 我不太确定我是否得到你的问题。你只是想要一个百分比值来给星星上色吗?
  • 等等,什么?为什么 5 颗星不只是每个值 20%?
  • 1星不是20%,2星40等吗?
  • @Ionic 不,我想将星星的每个评级作为百分比。例如:如果有 1 x 5 星级和 1 x 4 星级,则每颗星的评分为 50%。我希望你现在明白我的问题了。
  • 哦。所以star1 是一星评级的数量。好的。

标签: php math formulas


【解决方案1】:

如果您的目标是获得(例如)1 星的评分百分比,那么只需将star1 除以评分数(我猜是tot_stars,尽管名称似乎暗示其他意思)。这让你有一个比例;乘以 100 得到一个百分比。

因此,例如,让数据库进行数学运算:

SELECT star1, star1 * 100 / tot_stars AS percent1, 
       star2, star2 * 100 / tot_stars AS percent2, 
       star3, star3 * 100 / tot_stars AS percent3, 
       star4, star4 * 100 / tot_stars AS percent4, 
       star5, star5 * 100 / tot_stars AS percent5
  FROM starsTable

或者用 PHP 做:

<?php     
// Example data
$star1 = 1;
$star2 = 5;
$star3 = 7;
$star4 = 10;
$star5 = 8;

$tot_stars = $star1 + $star2 + $star3 + $star4 + $star5;

for ($i=1;$i<=5;++$i) {
  $var = "star$i";
  $count = $$var;
  $percent = $count * 100 / $tot_stars;
  for ($j=1;$j<=5;++$j) {
    echo $j <= $i ? "☆ " : "  ";
  }
  printf("\t%2d (%5.2f%%)\n", $count, $percent,2);
}
?>

哪个输出这个:

☆            1 ( 3.23%)
☆ ☆          5 (16.13%)
☆ ☆ ☆        7 (22.58%)
☆ ☆ ☆ ☆     10 (32.26%)
☆ ☆ ☆ ☆ ☆    8 (25.81%)

【讨论】:

  • 像魅力一样工作。非常感谢。
【解决方案2】:

我提出了一个解决方案,它是一个函数,它获取一个数组,其中有星星作为值。我们计算到总值,然后逐一计算百分比。我们返回百分比。每个百分比将对应于输入中具有相同索引的星号。

function getPercentages($inputValues) {
    $totalValues = 0;
    foreach ($inputValues as $inputValue) {
        $totalValues += $inputValue;
    }
    $outputValues = array();
    foreach ($inputValues as $key => $inputValue) {
        $outputValues[$key] = 100 * $inputValue / $totalValues;
    }
    return $outputValues;
}

【讨论】:

    【解决方案3】:

    好吧,我建议在您的数据库中进行数学运算并让它返回一个浮点值。这样您就可以轻松地以“百分比”样式显示星星。

    例子:

    SELECT (CAST(
              (star1*1) + (star2*2) + (star3)*3 + (star4*4) + (star5*5) 
            as float)/15) as percentageStars
    

    仅作为展示的示例:

    • 5 星:80-100
    • 4 星:60-80
    • 3 星:40-60
    • 2 星:20-40
    • 1 星:0-20

    由于您知道 1 颗星跨越 20 个点,因此您可以轻松地将 1 点作为 5% 的填充因子作为已回答星的填充因子。我想你以后会尝试将它转换为一个 css 属性以显示星色,对吧?

    示例: 你得到的评分是……好吧,lats 说 4.8。这意味着您可以只使用完整值作为总星数,即 4。之后您可以使用模 (%1) 来获得剩余值。例如,这个剩余值可以乘以 100 以获得 css 的百分比填充因子。

    公式: 4.8%1 = 0.8 * 100 = 80

    希望这对您有所帮助?

    【讨论】:

      猜你喜欢
      • 2020-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      相关资源
      最近更新 更多