134

如何通过关联键添加所有列值?请注意,键集是动态的。

输入数组:

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

期望的结果:

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

19 回答 19

215

您可以使用array_walk_recursive()为您的问题获取一般情况的解决方案(每个内部数组可能具有唯一键的解决方案)。

$final = array();

array_walk_recursive($input, function($item, $key) use (&$final){
    $final[$key] = isset($final[$key]) ?  $item + $final[$key] : $item;
});

array_walk_recursive()一般情况下的示例

此外,从PHP 5.5开始,您可以使用该array_column()函数来实现您想要的精确键结果,[gozhi]例如:

array_sum(array_column($input, 'gozhi')); 

array_column()指定键的示例

如果您想获得具有相同键的所有内部数组的总和(您发布的所需结果),您可以执行以下操作(请记住,第一个内部数组必须具有与其他数组相同的结构) :

$final = array_shift($input);

foreach ($final as $key => &$value){
   $value += array_sum(array_column($input, $key));
}    

unset($value);

array_column()以防所有内部数组具有相同键的示例

如果您想要使用array_column()then 的一般情况解决方案,首先您可以考虑获取所有唯一键,然后获取每个键的总和:

$final = array();

foreach($input as $value)
    $final = array_merge($final, $value);

foreach($final as $key => &$value)
    $value = array_sum(array_column($input, $key));

unset($value);

array_column()一般情况下的示例

于 2014-12-08T10:50:56.563 回答
99
$sumArray = array();

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

print_r($sumArray);
于 2009-09-30T08:04:47.873 回答
56

使用这个片段:

$key = 'gozhi';
$sum = array_sum(array_column($array,$key));
于 2018-03-17T09:04:41.853 回答
28

这是与其他两个类似的解决方案:

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

但这不需要检查数组键是否已经存在并且也不会抛出通知。

于 2009-09-30T08:28:46.680 回答
22

也可以使用array_map

$rArray = 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
    ),
);

$sumResult = call_user_func_array('array_map', array_merge(['sum'], $rArray));

function sum()
{
    return array_sum(func_get_args());
}
于 2012-03-30T06:47:05.397 回答
12
$newarr=array();
foreach($arrs as $value)
{
  foreach($value as $key=>$secondValue)
   {
       if(!isset($newarr[$key]))
        {
           $newarr[$key]=0;
        }
       $newarr[$key]+=$secondValue;
   }
}
于 2009-09-30T08:03:13.960 回答
5

另一个版本,下面有一些好处。

$sum = ArrayHelper::copyKeys($arr[0]);

foreach ($arr as $item) {
    ArrayHelper::addArrays($sum, $item);
}


class ArrayHelper {

    public function addArrays(Array &$to, Array $from) {
        foreach ($from as $key=>$value) {
            $to[$key] += $value;
        }
    }

    public function copyKeys(Array $from, $init=0) {
        return array_fill_keys(array_keys($from), $init);
    }

}

我想将 Gumbo、Graviton 和 Chris J 的最佳答案与以下目标结合起来,以便我可以在我的应用程序中使用它:

a)在循环(Gumbo)之外初始化'sum'数组键。应该有助于提高非常大的阵列的性能(尚未测试!)。消除通知。

b) 主要逻辑很容易理解,无需点击手册。(引力子,克里斯 J)。

c) 解决将任意两个具有相同键的数组的值相加的更一般的问题,并使其对子数组结构的依赖性降低。

与 Gumbo 的解决方案不同,您可以在值不在子数组中的情况下重用它。想象一下下面的示例,它$arr1不是$arr2硬编码的,而是作为在循环中调用函数的结果返回的。

$arr1 = array(
    'gozhi' => 2,
    'uzorong' => 1,
    'ngangla' => 4,
    'langthel' => 5
);

$arr2 = array(
   'gozhi' => 5,
   'uzorong' => 0,
   'ngangla' => 3,
   'langthel' => 2
);

$sum = ArrayHelper::copyKeys($arr1);

ArrayHelper::addArrays($sum, $arr1);
ArrayHelper::addArrays($sum, $arr2);
于 2012-02-20T10:55:30.400 回答
4

也可以使用array_walk

function array_sum_values(array $input, $key) {
   $sum = 0;
   array_walk($input, function($item, $index, $params) {
         if (!empty($item[$params[1]]))
            $params[0] += $item[$params[1]];
      }, array(&$sum, $key)
   );
   return $sum;
}

var_dump(array_sum_values($arr, 'gozhi'));

不像以前的解决方案那样可读,但它有效:)

于 2013-08-09T12:53:08.093 回答
4

遍历数组的每一项,并将值与先前的值相加(如果它们存在),如果不只是分配值。

<?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);

输出:

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

或者只是遍历每个子数组,并对每列的值进行分组。最终总结他们:

foreach($array as $subarray)
    foreach($subarray as $key => $value)
        $grouped[$key][] = $value;

$sums = array_map('array_sum', $grouped);
于 2019-01-12T19:32:30.763 回答
3

这是一个版本,其中两个数组的数组键可能不同,但您希望它们都存在于最终数组中。

function array_add_by_key( $array1, $array2 ) {
    foreach ( $array2 as $k => $a ) {
        if ( array_key_exists( $k, $array1 ) ) {
            $array1[$k] += $a;
        } else {
            $array1[$k] = $a;
        }
    }
    return $array1;
}
于 2013-12-11T23:36:16.180 回答
3

我们需要先检查数组键是否存在。

代码:

$sum = array();
foreach ($array as $key => $sub_array) {
    foreach ($sub_array as $sub_key => $value) {

        //If array key doesn't exists then create and initize first before we add a value.
        //Without this we will have an Undefined index error.
        if( ! array_key_exists($sub_key, $sum)) $sum[$sub_key] = 0;

        //Add Value
        $sum[$sub_key]+=$value;
    }
}
print_r($sum);

带有数组键验证的输出:

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

没有数组键验证的输出:

Notice: Undefined index: gozhi in F:\web\index.php on line 37

Notice: Undefined index: uzorong in F:\web\index.php on line 37

Notice: Undefined index: ngangla in F:\web\index.php on line 37

Notice: Undefined index: langthel in F:\web\index.php on line 37

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

这是一种不好的做法,尽管它会打印输出。始终首先检查密钥是否存在。

于 2017-11-22T06:17:10.237 回答
1

对于那些登陆这里并正在寻找合并N 个数组并且还对 N 个数组中找到的相同键的值求和的解决方案的人来说,我编写了这个也可以递归工作的函数。(见:https ://gist.github.com/Nickology/f700e319cbafab5eaedc )

例子:

$a = array( "A" => "bob", "sum" => 10, "C" => array("x","y","z" => 50) );
$b = array( "A" => "max", "sum" => 12, "C" => array("x","y","z" => 45) );
$c = array( "A" => "tom", "sum" =>  8, "C" => array("x","y","z" => 50, "w" => 1) );

print_r(array_merge_recursive_numeric($a,$b,$c));

将导致:

Array
(
    [A] => tom
    [sum] => 30
    [C] => Array
        (
            [0] => x
            [1] => y
            [z] => 145
            [w] => 1
        )

)

这是代码:

<?php 
/**
 * array_merge_recursive_numeric function.  Merges N arrays into one array AND sums the values of identical keys.
 * WARNING: If keys have values of different types, the latter values replace the previous ones.
 * 
 * Source: https://gist.github.com/Nickology/f700e319cbafab5eaedc
 * @params N arrays (all parameters must be arrays)
 * @author Nick Jouannem <nick@nickology.com>
 * @access public
 * @return void
 */
function array_merge_recursive_numeric() {

    // Gather all arrays
    $arrays = func_get_args();

    // If there's only one array, it's already merged
    if (count($arrays)==1) {
        return $arrays[0];
    }

    // Remove any items in $arrays that are NOT arrays
    foreach($arrays as $key => $array) {
        if (!is_array($array)) {
            unset($arrays[$key]);
        }
    }

    // We start by setting the first array as our final array.
    // We will merge all other arrays with this one.
    $final = array_shift($arrays);

    foreach($arrays as $b) {

        foreach($final as $key => $value) {

            // If $key does not exist in $b, then it is unique and can be safely merged
            if (!isset($b[$key])) {

                $final[$key] = $value;

            } else {

                // If $key is present in $b, then we need to merge and sum numeric values in both
                if ( is_numeric($value) && is_numeric($b[$key]) ) {
                    // If both values for these keys are numeric, we sum them
                    $final[$key] = $value + $b[$key];
                } else if (is_array($value) && is_array($b[$key])) {
                    // If both values are arrays, we recursively call ourself
                    $final[$key] = array_merge_recursive_numeric($value, $b[$key]);
                } else {
                    // If both keys exist but differ in type, then we cannot merge them.
                    // In this scenario, we will $b's value for $key is used
                    $final[$key] = $b[$key];
                }

            }

        }

        // Finally, we need to merge any keys that exist only in $b
        foreach($b as $key => $value) {
            if (!isset($final[$key])) {
                $final[$key] = $value;
            }
        }

    }

    return $final;

}

?>
于 2015-05-29T11:44:32.767 回答
0

你可以试试这个:

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

最后:

print_r($c);
于 2015-11-20T08:59:01.403 回答
0

在这里,您可以了解我通常如何进行此类操作。

// 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);
于 2015-11-20T09:02:13.413 回答
0

这对我的 laravel 项目很有效

print_r($Array); // your original array

$_SUM = [];

// count($Array[0]) => if the number of keys are equall in all arrays then do a count of index 0 etc.
for ($i=0; $i < count($Array[0]); $i++) {
    $_SUM[] = $Array[0][$i] + $Array[1][$i]; // do a for loop on the count 
}

print_r($_SUM); // get a sumed up array
于 2017-11-21T14:09:17.803 回答
-1
$sumArray = array();
foreach ($myArray as $k => $subArray) {
    foreach ($subArray as $id => $value) {
        if (!isset($sumArray[$id])) {
            $sumArray[$id] = 0;
        }
        $sumArray[$id]+=$value;
    }
}
于 2016-12-30T08:29:31.147 回答
-1
$sumArray = array();

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

print_r($sumArray);

`
于 2017-10-12T17:59:01.963 回答
-1

此处的示例数组

代码在这里:

        $temp_arr = [];
        foreach ($a as $k => $v) {
            if(!is_null($v)) {
                $sum = isset($temp_arr[$v[0]]) ? ((int)$v[5] + $sum) : (int)$v[5];
                $temp_arr[$v[0]] = $sum;
            }
        }
        return $temp_arr;

结果:

{SEQ_OK: 1328,SEQ_ERROR: 561}
于 2020-08-31T15:29:50.760 回答
-2

例如,您可以从下面这样的结果中提取所有字段。

我从数组中挑选出“余额”并保存到变量中

$kii =   $user->pluck('balance');

然后在下一行你可以这样总结:

$sum =  $kii->sum(); 

希望能帮助到你。

于 2019-01-03T17:15:18.037 回答