php合并两个二维数组,如果两个二维数组的id值相等,则合并为一个新的数组?
数组一:Array([0]=>Array([id]=>1[name]=>test)[1]=>Array([id]=>2[name]=>test2)[2]=>Array([...
数组一:
Array
(
[0] => Array
(
[id] => 1
[name] => test
)
[1] => Array
(
[id] => 2
[name] => test2
)
[2] => Array
(
[id] => 3
[name] => test3
)
)
数组二:
Array
(
[0] => Array
(
[id] => 1
[subject] => subject
)
[1] => Array
(
[id] => 3
[subject] => subject3
)
)
合并后的数组三:
Array
(
[0] => Array
(
[id] => 1
[name] => test
[subject] => subject
)
[1] => Array
(
[id] => 2
[name] => test2
)
[2] => Array
(
[id] => 3
[name] => test3
[subject] => subject3
)
) 展开
Array
(
[0] => Array
(
[id] => 1
[name] => test
)
[1] => Array
(
[id] => 2
[name] => test2
)
[2] => Array
(
[id] => 3
[name] => test3
)
)
数组二:
Array
(
[0] => Array
(
[id] => 1
[subject] => subject
)
[1] => Array
(
[id] => 3
[subject] => subject3
)
)
合并后的数组三:
Array
(
[0] => Array
(
[id] => 1
[name] => test
[subject] => subject
)
[1] => Array
(
[id] => 2
[name] => test2
)
[2] => Array
(
[id] => 3
[name] => test3
[subject] => subject3
)
) 展开
展开全部
id本应该是唯一性的键值,利用好就行。以下输出没有对id排序,因为觉得没必要。
需要时可以再排。
function mergeById(&$a,&$b){
$c=array();
foreach($a as $e) $c[$e['id']]=$e;
foreach($b as $e) $c[$e['id']]=isset($c[$e['id']])? $c[$e['id']]+$e : $e;
return $c;
}
$a=//数组一;
$b=//数组二;
var_dump(mergeById($b,$a));
===========
array
1 =>
array
'id' => int 1
'name' => string 'test' (length=4)
'subject' => string 'subject' (length=7)
2 =>
array
'id' => int 2
'name' => string 'test2' (length=5)
3 =>
array
'id' => int 3
'name' => string 'test3' (length=5)
'subject' => string 'subject3' (length=8)
需要时可以再排。
function mergeById(&$a,&$b){
$c=array();
foreach($a as $e) $c[$e['id']]=$e;
foreach($b as $e) $c[$e['id']]=isset($c[$e['id']])? $c[$e['id']]+$e : $e;
return $c;
}
$a=//数组一;
$b=//数组二;
var_dump(mergeById($b,$a));
===========
array
1 =>
array
'id' => int 1
'name' => string 'test' (length=4)
'subject' => string 'subject' (length=7)
2 =>
array
'id' => int 2
'name' => string 'test2' (length=5)
3 =>
array
'id' => int 3
'name' => string 'test3' (length=5)
'subject' => string 'subject3' (length=8)
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询