Reputation: 18200
Let's say I have a model collection that I'm mapping through like this:
$alreadyImported = [];
$players = Players::whereNotIn('id', $alreadyImported)
->get()
->random(25)
->pluck('id');
$groups = $players->map(function ($item, $key) use ($alreadyImported) {
array_merge($alreadyImported, $item->id);
$group = [
'username' => $item['username'],
];
return $group;
});
// $groups is a pivot table with group and players
Why does my $globalList
always start at []
? How can I carry the already-merged $globalList
to the next map iteration?
The player IDs does not matter. It's for show. I am looking to pass the array through the map iterations.
Upvotes: 0
Views: 204
Reputation: 163748
Just use pluck()
to get IDs from the collection:
$ids = $players->pluck('id');
Or, if you just need IDs:
$ids = Players::where('banned', false)->pluck('id');
If you're going to add any other data, you don't need to merge it to some array or a collection because map()
will create a new collection.
Finally, you don't need to use collect()
because get()
will return collection.
Upvotes: 2