2014-09-22 58 views
0

可以說我有兩個數組:array_merge兩個相同的陣列:你重置右側導致左側不露面

$a = array(
    'product' => array(
     'name' => "Some Product Name", 
     'description' => 'Some Product Description', 
     'productLink' => 'some.uri.url' 
    ) 
); 

$b = array(
    'product' => array(
     'name' => 'Some Product Name', 
     'description' => 'Some other Description', 
     'price' => 10.95, 
     'tax' => 0.08, 
    ) 
); 

我想這兩個陣列組合,但希望保持側$一個完整的名稱和說明。我認爲:

unset($b['product']['name']); 
unset($b['product']['description']); 
$c = array_merge($a, $b); 

應導致:

$c = array(
    'product' => array(
     'name' => "Some Product Name", 
     'description' => 'Some Product Description', 
     'productLink' => 'some.uri.url', 
     'price' => 10.95, 
     'tax' => 0.08, 
    ) 
); 

buuuut我看到這一點:

$c = array (
    'product' => array (
     'price' => 10.95, 
     'tax' => 0.08, 
    ), 
); 

這是一個錯誤?

回答

0

試試這個:

<?php 

$a = array(
    'product' => array(
     'name' => "Some Product Name", 
     'description' => 'Some Product Description', 
     'productLink' => 'some.uri.url' 
    ) 
); 

$b = array(
    'product' => array(
     'name' => 'Some Product Name', 
     'description' => 'Some other Description', 
     'price' => 10.95, 
     'tax' => 0.08, 
    ) 
); 

unset($b['product']['name']); 
unset($b['product']['description']); 
$c = array_merge($a['product'], $b['product']); 

print_r($c); 

我認爲當你把它合併覆蓋在第一層...所以從$ B「產品」是覆蓋從$一個「產品」。

0

仔細分析,你會意識到你要合併兩個數組,而不是數組本身的product關鍵,所以這應該工作(請注意,我換$b第一和$a秒所以$a值優先):

$c['product'] = array_merge($b['product'],$a['product']); 
print_r($c); 

打印:

Array 
(
    [product] => Array 
     (
      [name] => Some Product Name 
      [description] => Some Product Description 
      [productLink] => some.uri.url 
      [price] => 10.95 
      [tax] => 0.08 
     ) 

) 
0

@koala_dev,你是正確的,我是想合併這些按鍵,但這是陣列和m個嵌套數組的一小集我必須更換更大的數據集。在我的研究和測試中(現在我已經睡眠了),array_merge只會將數組的第一層從左到右合併,並將數組替換爲第一次覆蓋,但不是遞歸覆蓋。

array_merge_recursive也無法正常工作,因爲如果它發現兩個相似的鍵,那麼當數組的結構非常關鍵時,它將使用這些鍵創建另一個數組。

array_replace_recursive的確有沒有做什麼,我是有一點需要注意想:如果數組是數字鍵的第二陣列的值將取代左手陣列的數字鍵:

$ab = array('one' => 1, 'two' => 2, 'three' => 3); 
$cd = array(1, 2, 3); 
$ef = array('one' => 10, 'two' => 3, 'four' => 40); 
$zz = array_replace_recursive($ab, $cd, $ef); 

將導致:

array (
    'one' => 10, 
    'two' => 3, 
    'three' => 3, 
    0 => 1, 
    1 => 2, 
    2 => 3, 
    'four' => 40, 
)