Home > php教程 > php手册 > php中对2个数组相加的函数_php入门_脚本之家

php中对2个数组相加的函数_php入门_脚本之家

WBOY
Release: 2016-06-06 20:37:37
Original
1112 people have browsed it

php中对2个数组相加的函数代码,需要的朋友可以参考下。

代码如下:
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);
?>
Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template