简体   繁体   中英

How can I add an item into a Laravel Eloquent Collection by index?

I tried the following but it doesn't work.

$index = 2;
$collection->put($index, $item4);

For example if $collection looks like this:

$collection = [$item1, $item2, $item3];

I'd like to end up with:

$collection = [$item1, $item2, $item4, $item3];

The easiest way would probably be to splice it in, like this:

$collection->splice(2, 0, [$item4]);

Collections usually support the same functionality as regular PHP arrays. In this case, it's the array_splice() function that's used behind the scenes.

By setting the second parameter to 0, you essentially tell PHP to "go to index 2 in the array, then remove 0 elements, then insert this element I just provided you with".

To elaborate a little on Joel's answer:

  • splice modifies original collection and returns extracted elements
  • new item is typecasted to array, if that is not what we want we should wrap it in array

Then to add $item at index $index :

$collection->splice($index, 0, [$item]);

or generally:

$elements = $collection->splice($index, $number, [$item1, $item2, ...]);

where $number is number of elements we want to extract (and remove) from original collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM