二维数组相同键里的值相加
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)); ?>
以上是关于二维数组相同键里的值相加的主要内容,如果未能解决你的问题,请参考以下文章