0

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.

1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I am not looking for player IDs. I am looking to pass an array through a map iteration. The Ids was just an example.
@nn2 well, you haven't explained what exactly do you want to achieve. And as I said in the answer, you don't need to pass an array.
I clearly state it in the post. Every time a map iteration starts, $globalList = [] is reinitialized as []. How do I carry the merged-array over to the next iteration?
@nn2 if you want to reinvent the wheel, follow the link greener gave you in the comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.