php 递归合并多维数组

作者:freebeacon 分类: php 发布于:2017-9-26 17:13 ė45次浏览 60条评论
/*
 * 将A,B两个多维数组合并为C数组
 * A,B数组均为关联数组
 * 若key在A,B中均存在,若value都不是数组,取A的值
 * 若key在A,B中均存在,若其中一个value为数组,取数组的值
*/

$a = array(
	"1" => array(
		"1" => "a11",
		"2" => array(
			"1" => "a121",
			"2" => "a122",
		),
	),
	"2" => array(
		"1" => "b21",
		"2" => "b22",
	),
	"5" => 'e1',
);
$b = array(
	"1" => array(
		"1" => "a11",
		"2" => array(
			"1" => "a121",
			"2" => "a122",
			"3" => "a123",
		),
		"3" => "a13"
	),
	"2" => array(
		"1" => "b21",
		"2" => "b22",
		"3" => "b23",
	),
	"3" => array(
		"1" => "c31",
		"2" => "c32",
		"3" => "c33",
	),
	"4" => array(
		"1" => "d41",
		"2" => "d42",
		"3" => "d43",
	),
	"5" => 'e2',
	"6" => array(
		"1" => "f61",
		"2" => "f62",
	),
);


function my_merge(&$a,$b){

	foreach($a as $key=>&$val){
		if(is_array($val) && array_key_exists($key, $b) && is_array($b[$key])){
			my_merge($val,$b[$key]);
			$val = $val + $b[$key];
		}else if(is_array($val) || (array_key_exists($key, $b) && is_array($b[$key]))){
			$val = is_array($val)?$val:$b[$key];
		}
	}
	$a = $a + $b;
}
my_merge($a, $b);
echo '<pre>';print_r($a);
exit;

本文出自 港湾灯塔,转载时请注明出处及相应链接。

发表评论

电子邮件地址不会被公开。必填项已用*标注


Ɣ回顶部