我试图找出如何处理我的数组以使用其值进行“一些数学运算”。 该数组看起来类似于:
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%。
值应四舍五入到小数点后3位。有人可以为我提供array_walk(或foreach)功能吗?我只是想不出来。
最终数组应如下所示:
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%
)
...
)
谢谢!
答案 0 :(得分:4)
假设$arr
是您的初始数组,$new_arr
将是新数组。
$new_arr = array();
foreach ($arr as $i=>$ar)
foreach ($ar as $j=>$a)
$new_arr[$i][$j] = round(($a/array_sum($ar))*100, 1);
答案 1 :(得分:3)
array_walk()变体:
$data = array(
array(
'person1' => 71,
'person2' => 49,
'person3' => 15,
),
array(
'person1' => 56,
'person3' => 43,
'person4' => 21,
'person5' => 9,
'person6' => 7,
),
);
array_walk(
$data,
function (&$value) {
$sum = array_sum($value);
array_walk(
$value,
function (&$value) use ($sum) {
$value = round($value / $sum, 3) * 100 . '%';
}
);
}
);
var_dump($data);
注意array_walk()修改原始数组;如果您希望保持不变,请使用array_map()代替
答案 2 :(得分:1)
您可以使用array_sum()
添加这些值,然后计算每个值的比率/百分比并添加到新数组中:
$output = array();
foreach($array as $key => $current) {
$total = array_sum($current);
$output[$key] = array();
foreach($current as $person => $value) {
// decimal: round to 3 places
$output[$key][$person] = round($value / $total, 3);
// if you want a percentage, round to another 1 place (as per your example):
// $output[$key][$person] = round($output[$key][$person] * 100, 1) . '%';
}
}
修改: here's a demo