求和值在多维php数组



我试图找出如何处理我的数组做"一些数学"与它的值。数组看起来像这样:

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%
    )
...
)

谢谢!

假设$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);

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()代替

您可以使用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) . '%';
    }
}

编辑:这里是一个演示

相关内容

  • 没有找到相关文章

最新更新