PHP array merge on Inner keys -


i have 2 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 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 function: array_merge_recursive response wasn't 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 decided write own function:

function merge ($a, $b) {     $keys = array_keys($a);     foreach ($keys $value) {         if (isset($b[$value])) {             $tmp = array_keys($b[$value]);             foreach ($tmp $val){                 $a[$value][$val] = $b[$value][$val];             }         }     }     return $a; } print_r(merge($a, $b)); 

and got 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 works fine little arrays doesn't work big arrays, question is: how optimize function? because complexity grow depending on merged keys.

using php 7.0

you can use array_replace_recursive() instead.

array_replace_recursive($a, $b); 

demo: https://3v4l.org/bfiz2


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -