总结多维php数组中的值 [英] Sum up values in multidimensional php array
本文介绍了总结多维php数组中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图弄清楚如何处理我的数组以对其值进行一些数学运算". 该数组看起来类似于:
I try to figure out how to handle my array to do "some math" with its values. The array looks similar to this:
Array
(
[0] => Array
(
[person1] => 71
[person2] => 49
[person3] => 15
)
[1] => Array
(
[person1] => 56
[person3] => 43
[person4] => 21
[person5] => 9
[person6] => 7
)
...
)
每个值应除以总量: 因此,第一个值应为71/(71 + 49 + 15)= 0.526或52.6%.
Each value should be divided by the total amount: The first value should therefore be 71/(71+49+15)=0.526 or 52.6%.
值应四舍五入到小数点后三位.有人可以给我提供array_walk(或foreach)函数吗?我只是想不通.
The values should be rounded to 3 decimal places. Can someone provide me with an array_walk (or foreach) function? I just can't figure it out.
最终数组应如下所示:
Array
(
[0] => Array
(
[person1] => 52.6%
[person2] => 36.3%
[person3] => 11.1%
)
[1] => Array
(
[person1] => 41.2%
[person3] => 31.6%
[person4] => 15.4%
[person5] => 6.6%
[person6] => 5.1%
)
...
)
谢谢!
推荐答案
假定$arr
是您的初始数组,而$new_arr
将是新数组.
Assuming $arr
is your initial array, and $new_arr
will be the new one.
$new_arr = array();
foreach ($arr as $i=>$ar)
foreach ($ar as $j=>$a)
$new_arr[$i][$j] = round(($a/array_sum($ar))*100, 1);
这篇关于总结多维php数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文