如何通过索引将项目添加到 Laravel Eloquent 集合中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27733020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I add an item into a Laravel Eloquent Collection by index?
提问by rotaercz
I tried the following but it doesn't work.
我尝试了以下但它不起作用。
$index = 2;
$collection->put($index, $item4);
For example if $collection looks like this:
例如,如果 $collection 看起来像这样:
$collection = [$item1, $item2, $item3];
I'd like to end up with:
我想结束:
$collection = [$item1, $item2, $item4, $item3];
回答by Joel Hinz
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.
集合通常支持与常规 PHP 数组相同的功能。在这种情况下,它是在幕后使用的array_splice()函数。
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".
通过将第二个参数设置为 0,您实际上是告诉 PHP“转到数组中的索引 2,然后删除 0 个元素,然后插入我刚刚提供给您的这个元素”。
回答by Paul
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
splice
修改原始集合并返回提取的元素- 新项目被类型转换为数组,如果这不是我们想要的,我们应该将它包装在数组中
Then to add $item
at index $index
:
然后$item
在索引处添加$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.
哪里$number
是我们想要从原始集合中提取(和删除)的元素数量。