I have two arrays like:
$team = [
['id' => 1, 'name' => 'Team A'],
['id' => 2, 'name' => 'Team B'],
['id' => 3, 'name' => 'Team C'],
];
$people = [
['id' => 1, 'name' => 'Mark Hamill', 'team' => 1],
['id' => 2, 'name' => 'Nicolas Cage', 'team' => 2],
['id' => 3, 'name' => 'Tom Cruise', 'team' => 3],
['id' => 4, 'name' => 'Tom Hanks', 'team' => 1],
['id' => 5, 'name' => 'Brad Pitt', 'team' => 2],
['id' => 6, 'name' => 'Paul Smith', 'team' => 3],
['id' => 7, 'name' => 'Matt Daemon', 'team' => 1],
['id' => 8, 'name' => 'Robert Redford', 'team' => 2],
]
I would like to merge the $people array into the $team array as a child node based on the team id. So the result would be:
$team = [
[
'id' => 1,
'name' =>'Team A',
'members' => [
['id' => 1, 'name' => 'Mark Hamill', 'team' => 1],
['id' => 4, 'name' => 'Tom Hanks', 'team' => 1],
['id' => 7, 'name' => 'Matt Daemon', 'team' => 1],
]
],
[
'id' => 2,
'name' =>'Team B',
'members' => [
['id' => 2, 'name' => 'Nicolas Cage', 'team' => 2],
['id' => 5, 'name' => 'Brad Pitt', 'team' => 2],
['id' => 8, 'name' => 'Robert Redford', 'team' => 2],
]
],
[
'id' => 3,
'name' =>'Team C',
'members' => [
['id' => 3, 'name' => 'Tom Cruise', 'team' => 3],
['id' => 6, 'name' => 'Paul Smith', 'team' => 3],
]
],
];
I know I can loop through $team and add the relevant $people one at a time based on their 'team' id, but I was wondering if there was a more efficient way of doing this. In my project, either of the arrays could grow to contain up to around 50 items each and processing these one at a time is really slowing the page down.
Thanks