计算5个评级的平均评级

时间:2015-01-19 15:38:37

标签: php

如何计算这个数组:

$ratings = [
    1 => 220,
    2 => 31,
    3 => 44,
    4 => 175,
    5 => 3188
];

对一个数字(平均投票)如:

4

3.5

3 个答案:

答案 0 :(得分:2)

计算平均值的基本方法是简单地添加所有内容,并将其除以值的总数,因此:

$total = array_sum($ratings);
$avg = $total/count($ratings);
printf('The average is %.2f', $avg);

同样的逻辑适用于您的价值观,只有您需要平均评分,所以让我们得到已经给出的总数"评分点" ,并除以他们按总票数:

$totalStars = 0;
$voters = array_sum($ratings);
foreach ($ratings as $stars => $votes)
{//This is the trick, get the number of starts in total, then
 //divide them equally over the total nr of voters to get the average
    $totalStars += $stars * $votes;
}
printf(
    '%d voters awarded a total of %d stars to X, giving an average rating of %.1f',
    $voters,
    $totalStars,
    $totalStars/$voters
);

尽可能see here,输出为:

  

3658名选民共向X授予17054颗星,平均评分为4.7

答案 1 :(得分:0)

添加220倍于1的评级,31倍于2的评级,依此类推。然后除以总数。

<?php

$ratings = Array (
    1 => 220,
    2 => 31,
    3 => 44,
    4 => 175,
    5 => 3188
);

$max = 0;
$n = 0;
foreach ($ratings as $rate => $count) {
    echo 'Seen ', $count, ' ratings of ', $rate, "\n";
    $max += $rate * $count;
    $n += $count;
}

echo 'Average rating: ', $max / $n, "\n";

?>

答案 2 :(得分:0)

将总星数除以总票数:

$average = array_sum(array_map(
        function($nbStars, $howManyVotes) {
            return $nbStars * $howManyVotes;
        },
        array_keys($ratings),         // the stars: 1, 2, ... 5
        array_values($ratings)        // the votes for each nb. of stars
    )) / array_sum(array_values($ratings));