数组中的Sum数组并返回一个新数组

时间:2016-03-11 08:19:17

标签: php arrays sum

我有两个看起来像这样的数组:

$r1[$db_rate_type] = Array($db_rate_in, $db_rate_out, $db_rate_desc);
$r2[$db_rate_type] = Array($db_rate_in, $db_rate_out, $db_rate_desc);

让我们说每个数组的值如下所示:

Array 1:
[1] = [1400] [20] ["Standard timelønn"]
[2] = [NULL] [20] ["Kveldstillegg"]

Array 2:
[1] = [NULL] [20] ["Standard timelønn"]
[2] = [1500] [20] ["Kveldstillegg"]

如何对数组的值求和,但将计数ID保留在开头?

我尝试过以下代码:

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

但它只计算添加到另一个数组的一个数组,而不是数组WITHIN数组。我更喜欢退回的内容如下:

Array returned:
[1] = [1400] [40] ["Standard timelønn"]
[2] = [1500] [40] ["Kveldstillegg"]

那么我怎么能这样做,但尽可能有效呢?

可以找到数据库提取等的完整代码here

2 个答案:

答案 0 :(得分:1)

5.6的示例(需要参数解包)

<?php

$r1 = [
    1 => [1, 2, "one"],
    2 => [5, 5, "two"],
];
$r2 = [
    1 => [null, 20, "one"],
    2 => [1, 0, "two"],
];

$sum = function (array $a1, array $a2) {
    return array_map(
        function($e1) {
            return (is_int($e1) || is_null($e1)) ? array_sum(func_get_args()) : $e1;
        },
        $a1,
        $a2
    );
};


$res = [];
foreach ($r1 as $k => $a) {
    $res[$k] = $sum($r1[$k], $r2[$k]);
}

var_dump($res);

// Output:
array(2) {
  [1] =>
  array(3) {
    [0] =>
    int(1)
    [1] =>
    int(22)
    [2] =>
    string(3) "one"
  }
  [2] =>
  array(3) {
    [0] =>
    int(6)
    [1] =>
    int(5)
    [2] =>
    string(3) "two"
  }
}

https://3v4l.org/i10rJ

答案 1 :(得分:0)

我希望这有帮助。

<?php
//your needs
/* 
$d = array(
    0 => array(1400, 40, 1500, 30),
    1 => array(1500, 40, null, 30)
);
*/

//a
$a = array(
    0 => array(1400,20,null,15),
    1 => array(null, 20, null, 15)
);

//b
$b = array(
    0 => array(null,20,1500,15),
    1 => array(1500, 20, null, 15)
);

//c
$c = array_map(function () {
    $args = func_get_args();
    $sumArray = array();
    foreach ($args as $k=>$subArray) {
        foreach ($subArray as $id=>$value) {
            @$sumArray[$id]+=$value;
        }
    }
    return $sumArray;
}, $a, $b);

//result
print_r($c);
?>

Result