1

I have found several similar topics but none answers exactly what I need. I want to add data to a specific key index of a multidiensional array - without adding a new array layer or deleting other array layers.

I have tried to solve it with array_merge and the normal add to array method.

This is my array:

$array = [
    'capital' => [
        'Germany' => 'Berlin',
        'Austria' => 'Vienna',
        'France' => 'Paris',
    ],
    'currency' => [
        'Germany' => 'Euro',
        'Austria' => 'Euro',
        'France' => 'Euro',
    ],
 ];

If I try

$newData2 = [
    'Italy' => 'Rome',
    'China' => 'Beijing',
];
$array['capital'][] = $newData2;

I get

$array = [
    'capital' => [
        'Germany' => 'Berlin',
        'Austria' => 'Vienna',
        'France' => 'Paris',
        [
            'Italy' => 'Rome',
            'China' => 'Beijing',
        ],
    ],
    'currency' => [
        'Germany' => 'Euro',
        'Austria' => 'Euro',
        'France' => 'Euro',
    ],
 ];

That's incorrect, the 2 new should be on the same array layer as the others.

If I use array_merge, the currency section of the array is deleted:

 array_merge($array['capital'], $newData2);

My array should look like this:

$array = [
    'capital' => [
        'Germany' => 'Berlin',
        'Austria' => 'Vienna',
        'France' => 'Paris',
        'Italy' => 'Rome',
        'China' => 'Beijing',
    ],
    'currency' => [
        'Germany' => 'Euro',
        'Austria' => 'Euro',
        'France' => 'Euro',
    ],
 ];
0

3 Answers 3

1
 $array['capital'] = array_merge($array['capital'], $newData2);

 print_r($array);
Sign up to request clarification or add additional context in comments.

Comments

1

You can try this

 $array['capital']['Italy'] = 'Rome';
 $array['capital']['China'] = 'Beijing';

Comments

1

You can try just adding second array to the capital key:

$array["capital"] += $newData2;

I should add that there is a difference between merge and + operator, and you should use the one that fits better your needs.

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.