我有以下数组$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
)
有没有办法计算每个元素的百分比。我试过这个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));
}
我的代码中是否有错误? 谢谢!
答案 0 :(得分:2)
尝试这样的事情:
// 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>';
}