我想用PHP中的鍵合併兩個數組。如果沒有爲任何數組定義鍵,它應該將值填零。我想要的解決方案,如用鍵合併兩個不同長度的數組,並用0填充空
array_merge_recursive($a1, $a2)
但它不會產生所需的輸出。我編碼如下。它的工作原理,但我想知道是否有任何其他良好和有效的解決方案,如array_merge_recursive()
;
function array_combine_zero_fill($a1,$a2){
$a3=array();
foreach($a1 as $k=>$v){
$a3[$k]['doc1']=$v;
$a3[$k]['doc2']=array_key_exists($k, $a2) ? $a2[$k]:0;
}
foreach($a2 as $k=>$v){
$a3[$k]['doc1']=array_key_exists($k, $a2) ? $a3[$k]['doc1']:0;
$a3[$k]['doc2']=$v;
}
return $a3;
}
的陣列結構就像下面
$a1 = array(
"apple"=>4,
"banana"=>2,
"mango"=>10,
"guava"=>1,
"cherry"=>3,
"grapes"=>7
);
$a2 = array(
"pista"=>77,
"cashew"=>65,
"almond"=>23,
"guava"=>34,
"cherry"=>54,
"grapes"=>48
);
所需的結果應該是這樣的
a3 = Array(
[apple] => Array([doc1] => 4, [doc2] => 0),
[banana] => Array([doc1] => 2, [doc2] => 0),
[mango] => Array([doc1] => 10, [doc2] => 0),
[guava] => Array([doc1] => 1, [doc2] => 34),
[cherry] => Array([doc1] => 3, [doc2] => 54),
[grapes] => Array([doc1] => 7, [doc2] => 48),
[pista] => Array([doc1] => 0, [doc2] => 77),
[cashew] => Array([doc1] => 0, [doc2] => 65),
[almond] => Array([doc1] => 0, [doc2] => 23)
);
後的陣列結構,我已經更新了陣列結構和輸出結構問題的預期輸出 –
一起。 – Prabhu
@Prabhu爲什麼你甚至循環數組1,如果你所做的只是將數組1中存在的任何鍵設置爲0。以葡萄爲例,在第一個循環中,將值設置爲7和48,但是在循環2中你將它們覆蓋到0和48 ...這沒有意義。 – Styphon