Let\'s say I have following arrays:
Array
(
[0] => Array
(
[id] => 5
[name] => Education
This can be easily done using the 3-parameter form of array_column to re-index your second
array by the id
value and then looping over the first
array, merging the contents of the matching second
value (where it exists):
$second = array_column($second, null, 'id');
foreach ($first as &$subject) {
$subject = array_merge($subject, $second[$subject['id']] ?? []);
}
Output:
Array
(
[0] => Array
(
[id] => 5
[name] => Education
[title] => Edu
)
[1] => Array
(
[id] => 4
[name] => Computers
[title] => Comp
)
[3] => Array
(
[id] => 7
[name] => Science
[title] => Sci
)
[4] => Array
(
[id] => 1
[name] => Sports
[title] => Sport
)
)
Demo on 3v4l.org
This has the advantage over Will B.'s answer of not re-indexing the first
array. It's also slightly faster (my tests show ~10%) due to only having one call to array_column
and none to array_values
.
Update
This code can actually be sped up even more by using the array union operator (+
) (thanks @mickmackusa):
$second = array_column($second, null, 'id');
foreach ($first as &$subject) {
$subject += $second[$subject['id']] ?? [];
}
The output of this code is the same as above, but it runs about 10% faster again.
Demo on 3v4l.org