Reputation: 103
I am trying to add a multidimensional array somewhere inside another multidimensional array. I have this code example to explain what I try to do and what goes wrong:
$a_base = [
'wop' =>
[
'tik' =>
[
'a' => 190,
'b' => 323,
'c' => 342
],
'tak' =>
[
'a' => 142,
'b' => 654,
'c' => 785
]
],
'wap' =>
[
'top' =>
[
'a' => 564,
'b' => 667,
'c' => 968
],
'top' =>
[
'a' => 603,
'b' => 694,
'c' => 102
]
]
];
$a_addon = [
'tok' =>
[
'a' => 883,
'b' => 993,
'c' => 878
]
];
array_push($a_base['wop'], $a_addon);
var_dump($a_base);
The result is this:
array(2) {
["wop"]=>
array(3) {
["tik"]=>
array(3) {
["a"]=>
int(190)
["b"]=>
int(323)
["c"]=>
int(342)
}
["tak"]=>
array(3) {
["a"]=>
int(142)
["b"]=>
int(654)
["c"]=>
int(785)
}
[0]=>
array(1) {
["tok"]=>
array(3) {
["a"]=>
int(883)
["b"]=>
int(993)
["c"]=>
int(878)
}
}
}
["wap"]=>
array(1) {
["top"]=>
array(3) {
["a"]=>
int(603)
["b"]=>
int(694)
["c"]=>
int(102)
}
}
}
But what I need is this (without the [0]=> array(1) {...}):
array(2) {
["wop"]=>
array(3) {
["tik"]=>
array(3) {
["a"]=>
int(190)
["b"]=>
int(323)
["c"]=>
int(342)
}
["tak"]=>
array(3) {
["a"]=>
int(142)
["b"]=>
int(654)
["c"]=>
int(785)
}
["tok"]=>
array(3) {
["a"]=>
int(883)
["b"]=>
int(993)
["c"]=>
int(878)
}
}
["wap"]=>
array(1) {
["top"]=>
array(3) {
["a"]=>
int(603)
["b"]=>
int(694)
["c"]=>
int(102)
}
}
}
I have tried other functions like array_combine et cetera, but without success. Can anyone help me how to do this?
Upvotes: 0
Views: 50
Reputation: 47874
An array union will work perfectly as a functionless array merging technique on your associative arrays.
Code: (Demo)
$a_base['wop'] += $a_addon;
Upvotes: 1
Reputation: 780798
Use array_merge()
$a_base['wop'] = array_merge($a_base['wop'], $a_addon);
Upvotes: 0