显示具有相同键的两个数组值的总和

时间:2017-05-14 17:34:33

标签: php

我有两个具有相同键的数组,这两个数组包含我的表的月份数据。我想要这个值的总和,并在另一个数组中返回相同的键值和

这是我的两个数组

ARRAY1

Array ( [0] => Array ( [0] => Jan [1] => 0 ) 
        [1] => Array ( [0] => Feb [1] => 22 ) 
        [2] => Array ( [0] => Mar [1] => 0 ) 
        [3] => Array ( [0] => Apr [1] => 9 ) 
        [4] => Array ( [0] => May [1] => 1 ) 
        [5] => Array ( [0] => Jun [1] => 0 ) 
        [6] => Array ( [0] => Jul [1] => 0 ) 
        [7] => Array ( [0] => Aug [1] => 0 ) 
        [8] => Array ( [0] => Sep [1] => 0 ) 
        [9] => Array ( [0] => Oct [1] => 0 ) 
        [10] => Array ( [0] => Nov [1] => 0 ) 
        [11] => Array ( [0] => Dec [1] => 0 ) 
    )

阵列2:

Array ( [0] => Array ( [0] => Jan [1] => 0 ) 
        [1] => Array ( [0] => Feb [1] => 0 ) 
        [2] => Array ( [0] => Mar [1] => 18 ) 
        [3] => Array ( [0] => Apr [1] => 1 ) 
        [4] => Array ( [0] => May [1] => 1 ) 
        [5] => Array ( [0] => Jun [1] => 0 ) 
        [6] => Array ( [0] => Jul [1] => 0 ) 
        [7] => Array ( [0] => Aug [1] => 0 ) 
        [8] => Array ( [0] => Sep [1] => 0 ) 
        [9] => Array ( [0] => Oct [1] => 0 ) 
        [10] => Array ( [0] => Nov [1] => 0 ) 
        [11] => Array ( [0] => Dec [1] => 0 ) 
    )

我也尝试过使用这段代码

function sum_arrays($array1, $array2) {
    $array = array();
    foreach($array1 as $index => $value) {
        $array[$index] = isset($array2[$index]) ? $array2[$index] + $value : $value;
    }
    return $array;
}

我想要下面的结果

Array ( [0] => Array ( [0] => Jan [1] => 0 ) 
        [1] => Array ( [0] => Feb [1] => 22 ) 
        [2] => Array ( [0] => Mar [1] => 18 ) 
        [3] => Array ( [0] => Apr [1] => 10 ) 
        [4] => Array ( [0] => May [1] => 2 ) 
        [5] => Array ( [0] => Jun [1] => 0 ) 
        [6] => Array ( [0] => Jul [1] => 0 ) 
        [7] => Array ( [0] => Aug [1] => 0 ) 
        [8] => Array ( [0] => Sep [1] => 0 ) 
        [9] => Array ( [0] => Oct [1] => 0 ) 
        [10] => Array ( [0] => Nov [1] => 0 ) 
        [11] => Array ( [0] => Dec [1] => 0 ) 
    )

2 个答案:

答案 0 :(得分:1)

array_map方法(如果2个数组的项目按相同顺序排列):

// shortened array samples
$arr1 = [
    ["Jan", 0],
    ["Feb", 22],
    ["Mar", 0]
];

$arr2 = [
    ["Jan", 0],
    ["Feb", 0],
    ["Mar", 18]
];

$result = array_map(function($a, $b){
    return [$a[0], $a[1] + $b[1]];
}, $arr1, $arr2);

print_r($result);

输出:

Array
(
    [0] => Array
        (
            [0] => Jan
            [1] => 0
        )

    [1] => Array
        (
            [0] => Feb
            [1] => 22
        )

    [2] => Array
        (
            [0] => Mar
            [1] => 18
        )
)

答案 1 :(得分:0)

使用foreach循环:

$sum = 0;

foreach($items as $item) {
    $sum += $item['qty'];
}

echo $sum;

使用array_map():

echo array_sum(array_map(
    function($item) {
        return $item['qty'];
    }, $items)
);

使用array_reduce():

echo array_reduce($items, function($carry, $item) {
    $carry += $item['qty'];
    return $carry;
});