mtpultz
mtpultz

Reputation: 18248

Laravel 5.2 Push onto deeper indexed arrays within a Collection

Is there a way to put/merge on changes to a deeper index on a collection without converting the collection to an array first?

I have a $collection with 4 indices that all contain $arrays so in order to push onto the arrays I have to do this:

$collection = $collection->toArray(); // without this get array_push parameter 1 should be an array object given error
array_push($collection[$index], $array);

But, I was hoping there was a better way so I didn't have to re-collect(...) the original $collection before moving on, something like below, which I know wouldn't work, but forms an example of something less awkward then above:

$collection->get($index)->merge($array);

Upvotes: 0

Views: 680

Answers (3)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

As collections implements ArrayAccess interface, instead of:

$collection = $collection->toArray();
array_push($collection[$index], $array);

you can use:

array_push($collection[$index], $array);

EDIT

Okay, the code won't work because you get error that you cannot assign overloaded properties, but you mentioned also other error in comment.

Assume you have collection like this:

$collection = collect([[1,2],[11,12],[21,22],[31,32]]);

and you want to append 13 to [11,12].

You can do it like this:

$collection->put(1, array_merge($collection[1], [13]));

Upvotes: 1

Bogdan Koliesnik
Bogdan Koliesnik

Reputation: 900

It's very easy using put

$collection->put($index, $array);

That's it

If you want to push to the end of collection use push

$collection->push($array);

Upvotes: 0

mtpultz
mtpultz

Reputation: 18248

The solution I put in temporarily using array_push above didn't merge the array with an existing array, but this does work and seem a bit more elegant. Thanks to Marcin Nabialek who pointed out that Collections implement the ArrayAccess interface, which didn't solve the use of array_push, but was used in the answer below to override the exist array with the changes.

$collection[$index] = collect($collection->get($key))->merge($array);

I'm open to any improvements to push my use of Collections.

Upvotes: 0

Related Questions