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

后端 未结 20 2514
花落未央
花落未央 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:41
    $sumArray = array();
    
    foreach ($myArray as $k=>$subArray) {
      foreach ($subArray as $id=>$value) {
        $sumArray[$id]+=$value;
      }
    }
    
    print_r($sumArray);
    
    0 讨论(0)
  • 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.

    <?php
    $array = 
    [
        [
            'a'=>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);
    
    0 讨论(0)
提交回复
热议问题