2015-06-02 56 views
5

我想用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) 
); 
+2

後的陣列結構,我已經更新了陣列結構和輸出結構問題的預期輸出 –

+0

一起。 – Prabhu

+2

@Prabhu爲什麼你甚至循環數組1,如果你所做的只是將數組1中存在的任何鍵設置爲0。以葡萄爲例,在第一個循環中,將值設置爲7和48,但是在循環2中你將它們覆蓋到0和48 ...這沒有意義。 – Styphon

回答

5
// Find all unique keys 
$keys = array_flip(array_merge(array_keys($a1), array_keys($a2))); 

// create new array 
foreach($keys as $k=>$v) { 
    $result[$k]['doc1'] = isset($a1[$k]) ? $a1[$k] : 0; 
    $result[$k]['doc2'] = isset($a2[$k]) ? $a2[$k] : 0; 
    } 

    var_dump($result); 
+1

做得很好,很優雅。 – Styphon

+0

@Styphon即使一隻貓也喜歡一句善意的話:) – splash58

3

你的代碼是不是相當完整。試試這個:

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){ 
     // Only add to the array if it's not there, otherwise you just overwrite what was added in the first foreach above. 
     if (! isset($a3[$k])) { 
      $a3[$k]['doc1']=0; 
      $a3[$k]['doc2']=$v; 
     } 
    } 
    return $a3; 
} 
2
foreach(array_unique(array_keys(array_merge($a1,$a2))) as $k) 
{ 
    $output[$k]= array("doc1" => array_key_exists($k, $a1) ? $a1[$k] : 0, "doc2" => array_key_exists($k, $a2) ? $a2[$k] : 0); 
} 

print_r($output); 
相關問題