I have two arrays like:
$a = [
0 => [
'price' => 5.5
],
1 => [
'price' => 6.0
],
2 => [
'price' => 6.2
],
3 => [
'price' => 6.5
],
];
$b = [
0 => [
'color' => 'RED'
],
1 => [
'color' => 'WHITE'
],
2 => [
'color' => 'BLUE'
],
3 => [
'color' => 'RED'
],
];
I should have this response:
Array
(
[0] => Array
(
[price] => 5.5
[color] => RED
)
[1] => Array
(
[price] => 6
[color] => WHITE
)
[2] => Array
(
[price] => 6.2
[color] => BLUE
)
[3] => Array
(
[price] => 6.5
[color] => RED
)
)
I heard about the function: array_merge_recursive but the response wasn't the requiered:
Array
(
[0] => Array
(
[price] => 5.5
)
[1] => Array
(
[price] => 6
)
[2] => Array
(
[price] => 6.2
)
[3] => Array
(
[price] => 6.5
)
[4] => Array
(
[color] => RED
)
[5] => Array
(
[color] => WHITE
)
[6] => Array
(
[color] => BLUE
)
[7] => Array
(
[color] => RED
)
)
so I decided to write my own function:
function merge ($a, $b) {
$keys = array_keys($a);
foreach ($keys as $value) {
if (isset($b[$value])) {
$tmp = array_keys($b[$value]);
foreach ($tmp as $val){
$a[$value][$val] = $b[$value][$val];
}
}
}
return $a;
}
print_r(merge($a, $b));
and I got the proper response:
Array
(
[0] => Array
(
[price] => 5.5
[color] => RED
)
[1] => Array
(
[price] => 6
[color] => WHITE
)
[2] => Array
(
[price] => 6.2
[color] => BLUE
)
[3] => Array
(
[price] => 6.5
[color] => RED
)
)
The problem is that it works fine for little arrays but doesn't work good for big arrays, so my question is: how could I optimize the function? because the complexity would grow depending on merged keys.
Using PHP 7.0