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',
],
];