php合並二維數組
發布時間: 2025-03-30 04:43:18
1. php合並兩個二維數組,如果兩個二維數組的id值相等,則合並為一個新的數組
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_mp(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)
2. php 如何把多個一維數組合並成二維數組
你可以這樣操作,新建一個數組,然後用array_push()函數,依次把2個一維數據進行壓棧處理。然後就成了一個二維數組了。
熱點內容