php 如何对多维数组中的所有列值求和?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1496682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:49:21  来源:igfitidea点击:

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

phparraysmultidimensional-arraysum

提问by marknt15

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
)

采纳答案by Chris J

$sumArray = array();

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

print_r($sumArray);

回答by potashin

You can use array_walk_recursive()to get a general-case solution for your problem (the one when each inner array can possibly have unique keys).

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

$final = array();

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

Example with array_walk_recursive()for the general case

实施例与array_walk_recursive()对一般的情况下

Also, since PHP 5.5you can use the array_column()function to achieve the result you want for the exact key, [gozhi], for example :

此外,由于PHP 5.5,你可以使用array_column()函数来实现你想要的结果的精确关键字[gozhi]例如:

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

Example with array_column()for the specified key

使用array_column()指定键的示例

If you want to get the total sum of all inner arrays with the same keys (the desired result that you've posted), you can do something like this (bearing in mind that the first inner array must have the same structure as the others) :

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

$final = array_shift($input);

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

unset($value);

Example with array_column()in case all inner arrays have the same keys

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

If you want a general-case solution using array_column()then at first you may consider to get all unique keys , and then get the sum for each key :

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

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

Example with array_column()for the general case

实施例与array_column()对一般的情况下

回答by Gumbo

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.

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

回答by Tan Ory Jaka Perdana

Use this snippet:

使用这个片段:

$key = 'gozhi';
$sum = array_sum(array_column($array,$key));

回答by npcoda

It can also be done using array_map:

也可以使用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());
}

回答by Graviton

$newarr=array();
foreach($arrs as $value)
{
  foreach($value as $key=>$secondValue)
   {
       if(!isset($newarr[$key]))
        {
           $newarr[$key]=0;
        }
       $newarr[$key]+=$secondValue;
   }
}

回答by Todd Chaffee

Another version, with some benefits below.

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

$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);
    }

}

I wanted to combine the best of Gumbo's, Graviton's, and Chris J's answer with the following goals so I could use this in my app:

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

a) Initialize the 'sum' array keys outside of the loop (Gumbo). Should help with performance on very large arrays (not tested yet!). Eliminates notices.

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

b) Main logic is easy to understand without hitting the manuals. (Graviton, Chris J).

b) 主要逻辑很容易理解,无需阅读手册。(万有引力,克里斯 J)。

c) Solve the more general problem of adding the values of any two arrays with the same keys and make it less dependent on the sub-array structure.

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

Unlike Gumbo's solution, you could reuse this in cases where the values are not in sub arrays. Imagine in the example below that $arr1and $arr2are not hard-coded, but are being returned as the result of calling a function inside a loop.

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

回答by Filip Górczyński

It can also be done using array_walk:

也可以使用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'));

Not so readable like previous solutions but it works :)

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

回答by Bollis

Here's a version where the array keys may not be the same for both arrays, but you want them all to be there in the final array.

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

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;
}

回答by Bluetree

We need to check first if array key does exist.

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

CODE:

代码:

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

OUTPUT With Array Key Validation:

带有数组密钥验证的输出:

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

OUTPUT Without Array Key Validation:

没有数组密钥验证的输出:

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
)

This is a bad practice although it prints the output. Always check first if key does exist.

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