2

I'm trying to merge two arrays which have a custom key using array_push, but when I use array_push it removes the custom key.

For example if I just create a normal array with a custom key it works fine:

$price_arr = array();
$date = '2017-08-01';

$insert_data =  array(
    $date => array(
        'adult_1' => '10'
    )
);

print_r($insert_data);

The result is:

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

However if I use array push it removes the custom key, for example:

$price_arr = array();
$date = '2017-08-01';

$insert_data =  array(
    $date => array(
        'adult_1' => '10'
    )
);
array_push($price_arr, $insert_data);

$insert_data = array(
    $date => array(
        'child_1' => '2'
    )
);
array_push($price_arr, $insert_data);

print_r($price_arr);

The result is:

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

The result I'm trying to produce is:

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

Any help appreciated!

2 Answers 2

6

why not just do

$arr['custom_key'] = 'your value';

you do are not bound to use array_push , just assign it and it is done.

$price_arr = array();
$date = '2017-08-01';
$price_arr[$date]['adult_1'] = 10;
$price_arr[$date]['child_1'] = 2;
print_r($price_arr);
Sign up to request clarification or add additional context in comments.

Comments

2

You have to use array_merge instead of array_push

$price_arr = array();
$date = '2017-08-01';

$insert_data =  array(
    $date => array(
        'adult_1' => '10'
    )
);
$price_arr = array_merge($insert_data);

$insert_data = array(

    $date => array(
        'child_1' => '2'
        )
);

$price_arr[$date] = array_merge($price_arr[$date],$insert_data[$date]);

echo "<pre>";
print_r($price_arr);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.