如何通过索引将项目添加到Laravel雄辩收藏中? [英] How can I add an item into a Laravel Eloquent Collection by index?
本文介绍了如何通过索引将项目添加到Laravel雄辩收藏中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试过以下操作,但它不起作用。
I tried the following but it doesn't work.
$index = 2;
$collection->put($index, $item4);
例如,如果$ collection如下所示:
For example if $collection looks like this:
$collection = [$item1, $item2, $item3];
我想要结束:
$collection = [$item1, $item2, $item4, $item3];
推荐答案
最简单的方法可能是将其拼接,像这样:
The easiest way would probably be to splice it in, like this:
$collection->splice(2, 0, [$item4]);
集合通常支持与常规PHP数组相同的功能。在这种情况下,这是幕后使用的 array_splice()功能。
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.
通过将第二个参数设置为0,您基本上告诉PHP去数组中的索引2,然后删除0个元素,然后插入我刚才提供的元素。
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".
这篇关于如何通过索引将项目添加到Laravel雄辩收藏中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文