1. 程式人生 > >php 遞迴合併多維陣列

php 遞迴合併多維陣列

/*
 * 將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;