How to sum all column values in multi-dimensional

2020-01-22 11:25发布

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

Input array:

Array
(
    [0] => Array
        (
            [gozhi] => 2
            [uzorong] => 1
            [ngangla] => 4
            [langthel] => 5
        )

    [1] => Array
        (
            [gozhi] => 5
            [uzorong] => 0
            [ngangla] => 3
            [langthel] => 2
        )

    [2] => Array
        (
            [gozhi] => 3
            [uzorong] => 0
            [ngangla] => 1
            [langthel] => 3
        )
)

Desired result:

Array
(
    [gozhi] => 10
    [uzorong] => 1
    [ngangla] => 8
    [langthel] => 10
)

18条回答
Juvenile、少年°
2楼-- · 2020-01-22 11:49

Here is a solution similar to the two others:

$acc = array_shift($arr);
foreach ($arr as $val) {
    foreach ($val as $key => $val) {
        $acc[$key] += $val;
    }
}

But this doesn’t need to check if the array keys already exist and doesn’t throw notices neither.

查看更多
虎瘦雄心在
3楼-- · 2020-01-22 11:50
$sumArray = array();
foreach ($myArray as $k => $subArray) {
    foreach ($subArray as $id => $value) {
        if (!isset($sumArray[$id])) {
            $sumArray[$id] = 0;
        }
        $sumArray[$id]+=$value;
    }
}
查看更多
Luminary・发光体
4楼-- · 2020-01-22 11:51
$sumArray = array();

foreach ($myArray as $k=>$subArray) {
  foreach ($subArray as $id=>$value) {
    $sumArray[$id]+=$value;
  }
}

print_r($sumArray);
查看更多
Emotional °昔
5楼-- · 2020-01-22 11:51

Here you have how I usually do this kind of operations.

// We declare an empty array in wich we will store the results
$sumArray = array();

// We loop through all the key-value pairs in $myArray
foreach ($myArray as $k=>$subArray) {

   // Each value is an array, we loop through it
   foreach ($subArray as $id=>$value) {

       // If $sumArray has not $id as key we initialize it to zero  
       if(!isset($sumArray[$id])){
           $sumArray[$id] = 0;
       }

       // If the array already has a key named $id, we increment its value
       $sumArray[$id]+=$value;
    }
 }

 print_r($sumArray);
查看更多
【Aperson】
6楼-- · 2020-01-22 11:54

Use this snippet:

$key = 'gozhi';
$sum = array_sum(array_column($array,$key));
查看更多
相关推荐>>
7楼-- · 2020-01-22 11:54

You can try this:

$c = array_map(function () {
      return array_sum(func_get_args());
     },$a, $b);

and finally:

print_r($c);
查看更多
登录 后发表回答