I have the following array $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:
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>';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.