0

I have 3 separate arrays which are stored in one big array like so:

$date = '2017-08-01';

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

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

$price_arr_3 = array();
$price_arr_3[$date]['adult_3'] = 10;
$price_arr_3[$date]['child_3'] = 2;

$multiple_arrays[] = $price_arr_1;
$multiple_arrays[] = $price_arr_2;
$multiple_arrays[] = $price_arr_3;

print_r($multiple_arrays);

The output is:

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

I want to use array_merge_recursive() to merge the three arrays into one like this:

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

I think looping through the main array might work, but I can't get my head around it, appreciate any help!

I can't do the following because the number of arrays within the array is different each time:

print_r(array_merge_recursive($multiple_arrays[0],$multiple_arrays[1],$multiple_arrays[2]));
2
  • it will still work, isn't it? Commented Jul 30, 2017 at 12:49
  • You mean the last part where I'm using $multiple_arrays[0],$multiple_arrays[1]... ? The number of arrays in the array changes each time, so no it won't work Commented Jul 30, 2017 at 13:02

1 Answer 1

2

To pass to array_merge_recursive several arguments you can use call_user_func_array. In your case it will look like:

$date = '2017-08-01';

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

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

$price_arr_3 = array();
$price_arr_3[$date]['adult_3'] = 10;
$price_arr_3[$date]['child_3'] = 2;

$multiple_arrays[] = $price_arr_1;
$multiple_arrays[] = $price_arr_2;
$multiple_arrays[] = $price_arr_3;

//print_r($multiple_arrays);

$r = call_user_func_array('array_merge_recursive', $multiple_arrays);
print_r($r);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.