How can calculate this array:
$ratings = [
1 => 220,
2 => 31,
3 => 44,
4 => 175,
5 => 3188
];
To a number (the average vote) like:
4
or
3.5
How can calculate this array:
$ratings = [
1 => 220,
2 => 31,
3 => 44,
4 => 175,
5 => 3188
];
To a number (the average vote) like:
4
or
3.5
The basic way to calculate the average is simply to add everything up, and divide it by the total number of values, so:
$total = array_sum($ratings);
$avg = $total/count($ratings);
printf('The average is %.2f', $avg);
The same logic applies to your values, only you need the average rating, so let's get the total number "rating points" that were given, and divide them by the total number of votes:
$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
);
As you can see here, the output is:
3658 voters awarded a total of 17054 stars to X, giving an average rating of 4.7
Divide the total numbers of stars to the total number of votes:
$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));
Add 220 times a rating of 1, 31 times a rating of 2 and so on. Then divide by the total.
<?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";
?>