二维数组相同键里的值相加

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二维数组相同键里的值相加相关的知识,希望对你有一定的参考价值。

<?php 
header("Content-type: text/html; charset=utf-8");


$_data1=Array
(
    "0" => Array
        (
            "userid" => 1,
            "username" => ‘admin‘,
            "roleid" => ‘超级管理员‘,
            "has_number" => 23,
            "no_number" => 0,
            "all_number" => 92
        ),

    "1" => Array
        (
            "userid" => 5,
            "username" => ‘office‘,
            "roleid" => ‘总编‘,
            "has_number" => 56,
            "no_number" => 0,
            "all_number" => 56
        ),

    "2" => Array
        (
            "userid" => 6,
            "username" => ‘nyfzjt001‘,
            "roleid" => ‘编辑‘,
            "has_number" => 65,
            "no_number" => 6,
            "all_number" => 112
        )

    

);
$_data2=Array
(
    "0" => Array
        (
            "userid" => 1,
            "username" => ‘admin‘,
            "roleid" => ‘超级管理员‘,
            "has_number" => 23,
            "no_number" => 0,
            "all_number" => 92
        ),

    "1" => Array
        (
            "userid" => 5,
            "username" => ‘office‘,
            "roleid" => ‘总编‘,
            "has_number" => 56,
            "no_number" => 0,
            "all_number" => 56
        ),

    "2" => Array
        (
            "userid" => 6,
            "username" => ‘nyfzjt001‘,
            "roleid" => ‘编辑‘,
            "has_number" => 65,
            "no_number" => 6,
            "all_number" => 112
        )


    

);

//两数组值相加
$data=array();
function array_add($arr1,$arr2)
{
    foreach ($arr1 as $k1 => $v1) 
    {
        foreach ($arr2 as $k2 => $v2) 
        {
            if($k1==$k2)
            {
                $data[$k1][‘userid‘]=$v1[‘userid‘];
                $data[$k1][‘username‘]=$v1[‘username‘];
                $data[$k1][‘roleid‘]=$v1[‘roleid‘];
                $data[$k1][‘has_number‘]=$v2[‘has_number‘]+$v1[‘has_number‘];
                $data[$k1][‘no_number‘]=$v2[‘no_number‘]+$v1[‘no_number‘];
                $data[$k1][‘all_number‘]=$v2[‘all_number‘]+$v1[‘all_number‘];
            }
        }
        
    }

 return $data;

}

print_r(array_add($_data1,$_data2));


 ?>

 

以上是关于二维数组相同键里的值相加的主要内容,如果未能解决你的问题,请参考以下文章

java如果把Array中的数组的值进行相加呢?

PHP 想从1组二维数组里取1个下标的值去其他数组查询另1个下标的值,然后用查询出来值替换原来二维数组里的

PHP计算二维数组中一维数组相同键名的,键值相加

js数组相加

求问php两个二维数组中每个元素的相加

SQL中怎么修改主键里的属性这个主键和另一个表有外键约束