Home  >  Article  >  Backend Development  >  php中对2个数组相加的函数_PHP教程

php中对2个数组相加的函数_PHP教程

WBOY
WBOYOriginal
2016-07-21 15:28:131040browse

复制代码 代码如下:

function array_add($a,$b){
//根据键名获取两个数组的交集
$arr=array_intersect_key($a, $b);
//遍历第二个数组,如果键名不存在与第一个数组,将数组元素增加到第一个数组
foreach($b as $key=>$value){
if(!array_key_exists($key, $a)){
$a[$key]=$value;
}
}
//计算键名相同的数组元素的和,并且替换原数组中相同键名所对应的元素值
foreach($arr as $key=>$value){
$a[$key]=$a[$key]+$b[$key];
}
//返回相加后的数组
return $a;
}
$a = array('0'=>'2','1'=>'4','3'=>'8','a'=>'100');
$b = array('0'=>'5','2'=>'4','b'=>'33','a'=>'22');
$arr=array_add($a,$b);
print_r($arr);
?>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/323646.htmlTechArticle复制代码 代码如下: ?php function array_add($a,$b){ //根据键名获取两个数组的交集 $arr=array_intersect_key($a, $b); //遍历第二个数组,如果键名不存在...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn