2017-07-30 66 views
0

我想合併兩個數組,其中主鍵匹配,我試着使用array_merge但密鑰剛剛被覆蓋。PHP合併兩個數組,其中鍵匹配

例如,我有此數組:

$date = '2017-08-01'; 

$price_arr_1 = array(); 
$price_arr_1[$date]['adult_1'] = 10; 
$price_arr_1[$date]['child_1'] = 2; 
print_r($price_arr_1); 

,其輸出:

Array ([2017-08-01] => Array ([adult_1] => 10 [child_1] => 2)) 

我有此數組:

$date = '2017-08-01'; 

$price_arr_2 = array(); 
$price_arr_2[$date]['adult_2'] = 10; 
$price_arr_2[$date]['child_2'] = 2; 
print_r($price_arr_2); 

,其輸出:

Array ([2017-08-01] => Array ([adult_2] => 10 [child_2] => 2)) 

當我試圖把它們合併是這樣的:

print_r(array_merge($price_arr_1,$price_arr_2)); 

它輸出這樣的:

Array ([2017-08-01] => Array ([adult_2] => 10 [child_2] => 2)) 

我要輸出這樣的:

Array ([2017-08-01] => Array ([adult_1] => 10 [adult_2] => 10 [child_1] => 2 [child_2] => 2)) 

知道的任何想法,如何達到上述目的!

回答

1

您應該相對於日期($date)合併:

<?php 

$date = '2017-08-01'; 

$price_arr_1 = array(); 
$price_arr_1[$date]['adult_1'] = 10; 
$price_arr_1[$date]['child_1'] = 2; 
print_r($price_arr_1); 

$date = '2017-08-01'; 

$price_arr_2 = array(); 
$price_arr_2[$date]['adult_2'] = 10; 
$price_arr_2[$date]['child_2'] = 2; 
print_r($price_arr_2); 

print_r(array_merge($price_arr_1[$date],$price_arr_2[$date])); 

這裏是輸出:

Array 
(
    [2017-08-01] => Array 
     (
      [adult_1] => 10 
      [child_1] => 2 
     ) 

) 
Array 
(
    [2017-08-01] => Array 
     (
      [adult_2] => 10 
      [child_2] => 2 
     ) 

) 
Array 
(
    [adult_1] => 10 
    [child_1] => 2 
    [adult_2] => 10 
    [child_2] => 2 
) 

工作演示:https://eval.in/839408

1

你期待這樣的事情?

Try this code snippet here

<?php 

ini_set('display_errors', 1); 

$date = '2017-08-01'; 
$price_arr_1 = array(); 
$price_arr_1[$date]['adult_1'] = 10; 
$price_arr_1[$date]['child_1'] = 2; 

$date = '2017-08-01';  
$price_arr_2 = array(); 
$price_arr_2[$date]['adult_2'] = 10; 
$price_arr_2[$date]['child_2'] = 2; 

foreach($price_arr_1 as $someDate => $data) 
{ 
    if(isset($price_arr_2[$someDate])) 
    { 
     $price_arr_1[$someDate]=array_merge($price_arr_1[$someDate],$price_arr_2[$someDate]); 
    } 
    else 
    { 
     $price_arr_1[$someDate]=$price_arr_2[$someDate]; 
    } 
} 
print_r($price_arr_1); 
5

在這種情況下,你可以使用簡單的array_merge_recursive

$a1 = Array ('2017-08-01' => Array ('adult_1' => 10, 'child_1' => 2,)); 
$a2 = Array ('2017-08-01' => Array ('adult_2' => 20, 'child_2' => 4,)); 

echo'<pre>',print_r(array_merge_recursive($a1, $a2)),'</pre>'; 
0
更好

不是把一個創可貼在你的代碼,我會勸你完全改變你的方法。最簡單的,避免使用任何數組函數。在聲明每組元素時,只需構建結果數組。提高你的代碼的表現是這樣的:

代碼:(Demo

$date = '2017-08-01'; 

$prices[$date]=['adult_1'=>10,'child_1'=>2]; 
$prices[$date]+=['adult_2'=>10,'child_2'=>2]; // notice the + sign 

ksort($prices[$date]); // optionally, you can sort the subarrays ASC by key name 
var_export($prices); 

輸出:

array (
    '2017-08-01' => 
    array (
    'adult_1' => 10, 
    'adult_2' => 10, 
    'child_1' => 2, 
    'child_2' => 2, 
), 
)