phplaravellaravel-5laravel-collection

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);

Solution

  • 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.