最近做的一个项目要实现多个相同数组的相加合并功能,需要实现对应键名的键值相加,具体说明如下:

有如下多个数组:

array(13) {
  [14] => string(1) "4"
  [15] => string(1) "4"
  [16] => string(1) "4"
  [17] => string(1) "4"
  [18] => string(1) "4"
  [19] => string(2) "30"
  [20] => string(2) "10"
  [21] => string(1) "5"
  [22] => string(1) "2"
  [23] => string(1) "2"
  [24] => string(1) "1"
  [25] => string(2) "17"
  [26] => string(2) "10"
}
array(13) {
  [14] => string(1) "4"
  [15] => string(1) "4"
  [16] => string(1) "3"
  [17] => string(1) "3"
  [18] => string(1) "4"
  [19] => string(2) "30"
  [20] => string(2) "10"
  [21] => string(1) "5"
  [22] => string(1) "2"
  [23] => string(1) "1"
  [24] => string(1) "1"
  [25] => string(2) "15"
  [26] => string(2) "10"
}
array(13) {
  [14] => string(1) "3"
  [15] => string(1) "4"
  [16] => string(1) "4"
  [17] => string(1) "4"
  [18] => string(1) "4"
  [19] => string(2) "30"
  [20] => string(1) "5"
  [21] => string(1) "5"
  [22] => string(1) "2"
  [23] => string(1) "2"
  [24] => string(1) "1"
  [25] => string(2) "15"
  [26] => string(2) "10"
}

要合并为一个数组,其中对应项的值相加,得出的数组如下(以下数组只为示例,并非实际运算结果):

array(13) {
  [14] => int(11)
  [15] => int(12)
  [16] => int(14)
  [17] => int(14)
  [18] => int(16)
  [19] => int(118)
  [20] => int(34)
  [21] => int(19)
  [22] => int(8)
  [23] => int(7)
  [24] => int(4)
  [25] => int(65)
  [26] => int(38)
}

具体函数代码:


//数组相同键,值相加。
function array_value_sum(){
    $res = array();
    foreach (func_get_args() as $arr) {
        foreach ($arr as $k => $v){
            if (!isset($res[$k])){
                $res[$k] = $v;
            }else{
                $res[$k] += $v;
            }
        }
    }
    return $res;
}

调用方式:


$arr = array();
foreach ($array as $k => $v) {
    $v = json_decode($v,true);
    $arr = array_value_sum($v,$arr);
}
var_dump($arr);