我有以下数组:
[ratings] => Array
(
[0] => 3
[1] => 3
[2] => 2
[3] => 3
[4] => 3
[5] => 1
[6] => 3
[7] => 4
[8] => 5
)
获得每个评级百分比的最佳和最快方法是什么。例如,现在有9个评级,5个评级为“3”,因此评级“3”的百分比为55.55%。
答案 0 :(得分:4)
<?php
$array = array(3,3,2,3,3,1,3,4,5);
function array_avg($array, $round=1){
$num = count($array);
return array_map(
function($val) use ($num,$round){
return array('count'=>$val,'avg'=>round($val/$num*100, $round));
},
array_count_values($array));
}
$avgs = array_avg($array);
/*
* You can access any average/count like:
* echo "The count of 3 is: {$avgs[3]['count']}";
* echo "The average of 3 is: {$avgs[3]['avg']}";
*/
echo '<pre>'.print_r($avgs,1).'</pre>';
输出:
Array
(
[3] => Array
(
[count] => 5
[avg] => 55.6
)
[2] => Array
(
[count] => 1
[avg] => 11.1
)
[1] => Array
(
[count] => 1
[avg] => 11.1
)
[4] => Array
(
[count] => 1
[avg] => 11.1
)
[5] => Array
(
[count] => 1
[avg] => 11.1
)
)
答案 1 :(得分:3)
function findPercentage($r, $ratings){
$arr = array_count_values($ratings);
return $arr[$r]/count($ratings) * 100;
}
答案 2 :(得分:0)
$avg = array_sum($a)/count($a)
在Javascript中:
var a = [1,2,3,4,5,6];
var avg = a.reduce(function(a,b){ return a+b })/a.length;
答案 3 :(得分:0)
// $ratings is your array
function findPercentage($r, $ratings){
$count = 0; // count number of particular ratings
foreach ($ratings as $i){
if ($i == $r) $count++;
}
return $count/count($ratings) * 100;
}
示例:
echo findPercentages(3, $ratings);
答案 4 :(得分:0)
如评论所示,您可以使用array_count_values
并使用count
进行简单迭代处理。
在我的代码示例中,我将其包装到它自己的函数中:
$ratings = [3,3,2,3,3,1,3,4,5];
$percentages = function($ratings) {
$total = count($ratings);
$percentages = [];
foreach(array_count_values($ratings) as $value => $count) {
$percentages[$value] = $count / $total;
}
return $percentages;
};
print_r($percentages($ratings));
输出(Demo):
Array (
[3] => 0.55555555555556
[2] => 0.11111111111111
[1] => 0.11111111111111
[4] => 0.11111111111111
[5] => 0.11111111111111
)
我希望这能很好地证明这一点。再次(为了好玩):
print_r($percentages(array_map('strval', $percentages($ratings))));
(array_count_values()
只能计算STRING和INTEGER值)
输出:
Array (
[0.55555555555556] => 0.2
[0.11111111111111] => 0.8
)
答案 5 :(得分:-1)
$rating = array(3, 3, 5, 5, 3, 4);
$value = 0;
foreach ($rating as $i) {
$value += $i;
}
$percentage = $value / count($rating);
echo $percentage;
== 的更新强>
我写了一个小测试:
$rating = array();
echo "create array".PHP_EOL;
for ($i = 0; $i < 100000; $i++) {
$rating[] = rand(1, 5);
}
echo "foreach algorithm: ".PHP_EOL;
$time = microtime();
$value = 0;
foreach ($rating as $i) {
$value += $i;
}
$percentage = $value / count($rating);
echo $percentage.PHP_EOL;
echo "time is ".(microtime() - $time).PHP_EOL;
echo "array_sum algorithm: ".PHP_EOL;
$time = microtime();
$avg = array_sum($rating)/count($rating);
echo "time is ".(microtime() - $time).PHP_EOL;
和结果:
create array
foreach algorithm:
2.99924
time is 0.017117
array_sum algorithm:
time is 0.002819
答案:使用编写用户@Reflective的算法,使用函数 array_sum