我试图合并主键匹配的两个数组,我尝试使用array_merge,但键只是被覆盖。
例如我有这个数组:
$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 ) )
赞赏有关如何实现上述目标的任何想法!
答案 0 :(得分: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>';
答案 1 :(得分: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
)
答案 2 :(得分:1)
你期待这样的事吗?
<?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);
答案 3 :(得分: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,
),
)