How to sum all column values in multi-dimensional array?

后端 未结 20 2518
花落未央
花落未央 2020-11-22 00:57

How can I add all the columnar values by associative key? Note that key sets are dynamic.

Input array:

Arr         


        
20条回答
  •  盖世英雄少女心
    2020-11-22 01:42

    Go through each item of the array and sum values to previous values if they exist, if not just assign the value.

    1,
            'b'=>1,
            'c'=>1,
        ],
        [
            'a'=>2,
            'b'=>2,
        ],
        [
            'a'=>3,
            'd'=>3,
        ]
    ];
    
    $result = array_reduce($array, function($carry, $item) {
        foreach($item as $k => $v)
            $carry[$k] = $v + ($carry[$k] ?? 0);
    
        return $carry;
    }, []);
    
    print_r($result);
    

    Output:

    Array
    (
        [a] => 6
        [b] => 3
        [c] => 1
        [d] => 3
    )
    

    Or just loop through each sub array, and group the values for each column. Eventually summing them:

    foreach($array as $subarray)
        foreach($subarray as $key => $value)
            $grouped[$key][] = $value;
    
    $sums = array_map('array_sum', $grouped);
    

提交回复
热议问题