Pure php solution - use array_replace_recursive , like this:
array_replace_recursive( array_combine(array_column($color, "id"), $color), array_combine(array_column($size, "id"), $size) );
You should notice that array_replace_recursive joins arrays with keys. So, if you get such data from a database:
$color = [ ['id' => 1, 'color' => 'red'], ['id' => 2, 'color' => 'red'] ]; $size = [ ['id' => 2, 'size' => 'SM'] ];
array_replace_recursive returns a damaged merge:
$combined = [ ['id' => 2, 'color' => 'red', 'size' => 'SM'], ['id' => 2, 'color' => 'red'] ];
The solution is to combine array_replace_recursive with array_column and array_combine to combine arrays by their id field:
array_replace_recursive( array_combine(array_column($color, "id"), $color), array_combine(array_column($size, "id"), $size) );
array_combine(array_column($color, "id"), $color) creates an associative array with id as keys.
So in your case it will return:
$combined = [ 1 => ['id' => 1, 'color' => 'red', 'size' => 'SM'], 2 => ['id' => 2, 'color' => 'green', 'size' => 'XL'], 3 => ['id' => 3, 'color' => 'blue', 'size' => 'MD'], 4 => ['id' => 4, 'size' => 'LG'], ];