[英]Calculate the percentage of values in an array
I have the following array $browser
: 我有以下数组
$browser
:
Array
(
[2] => Array
(
[0] => Internet Explorer
[1] => 5809
)
[3] => Array
(
[0] => Chrome
[1] => 9205
)
[4] => Array
(
[0] => Safari
[1] => 5288
)
[5] => Array
(
[0] => Opera
[1] => 102
)
Is there a way to calculate for each element the percentage . 有没有办法计算每个元素的百分比。 I tried this funtcion:
我试过这个funtcion:
foreach ($browser as $key => $value){
print_array(array_avg($browser[$key][1]) );
}
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));
}
Is there an error in my code? 我的代码中有错误吗? Thanks!
谢谢!
Try something like this: 尝试这样的事情:
// calculate the sum; first transform the array in something with only integers, then sum that array
$sum = array_sum(array_map(function ($a) { return $a[1]; }, $browser));
// walk through the array, print the percentage (value / sum) for each browser
foreach ($browser as $info) {
echo 'Percentage for browser '.$info[0].' = '.round(($info[1]/$sum)*100).'%<br>';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.