前端技术 手机教程
程序开发 平面动画
系统软件 运营推广
CMS教程 在线手册
资源下载 网络安全
精准搜索请尝试:精确搜索

php数组相加合并函数,多个数组相同键名项键值相加。

2018-06-27 08:16:18 来源:原创 作者:寂静的神经

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

有如下多个数组:

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);
分享到:
本文关键词:函数 数组 相加 合并

相关文章

零五科技,分享IT知识,国内顶级IT知识门户网站。

Copyright (C) www.02405.com, All Rights Reserved.

零五科技 版权所有 辽ICP备13002105号-1

//百度 //cnzz