Let's say I have following arrays:
$first = [
['id' => 5, 'name' => 'Education'],
['id' => 4, 'name' => 'Computers'],
['id' => 7, 'name' => 'Science'],
['id' => 1, 'name' => 'Sports'],
];
$second = [
['id' => 1, 'title' => 'Sport'],
['id' => 7, 'title' => 'Sci'],
['id' => 4, 'title' => 'Comp'],
['id' => 5, 'title' => 'Edu'],
];
And desired output is:
[
['id' => 5, 'name' => 'Education', 'title' => 'Edu'],
['id' => 4, 'name' => 'Computers', 'title' => 'Comp'],
['id' => 7, 'name' => 'Science', 'title' => 'Sci'],
['id' => 1, 'name' => 'Sports', 'title' => 'Sport'],
]
I have managed to merge these arrays with simply:
foreach ($first as $key => $value) {
$result[$key] = array_merge($first[$key], $second[$key]);
}
But the output is combined by first level index instead of their id
value:
Array
(
[0] => Array
(
[id] => 5
[name] => Education
[title] => Sport
)
[1] => Array
(
[id] => 4
[name] => Computers
[title] => Sci
)
[3] => Array
(
[id] => 7
[name] => Science
[title] => Comp
[4] => Array
(
[id] => 1
[name] => Sports
[title] => Edu
)
)
I would like to append the title values from the second array to the first array where there is a matching id
value and maintain the sorting of the first array.
How can I achieve this?
You can just do a nested loop and check if the id
values match, then add title
to $first
(or name
to $second
)
foreach($first as $key => $value){
foreach($second as $value2){
if($value['id'] === $value2['id']){
$first[$key]['title'] = $value2['title'];
}
}
}