如何在Laravel中的特定索引处将对象插入到集合对象中

时间:2016-07-03 13:32:40

标签: laravel

我有一个包含新闻项目的集合,我想在特定索引中添加一个对象。例如:

$item = new NewsItem();
$newsItems->add($item); // to index nr 3

2 个答案:

答案 0 :(得分:0)

这是不可能的。

更好的解决方案是在索引处拼接您的集合,然后创建新集合,在索引之前复制集合,添加新项目,最后将集合的其余部分复制到新集合中。

$afterIndex = $newsItems->splice($index);
$newItensCollections = $newsItems;
$newItensCollections->prepend($yourNewItem);
$newItensCollections->union($afterIndex);

拼接: https://laravel.com/docs/master/collections#method-splice

前置: https://laravel.com/docs/master/collections#method-prepend

要复制数组: https://laravel.com/docs/master/collections#method-union

答案 1 :(得分:0)

您可以使用拼接在特定位置插入对象:

$newsItems->splice($index, 0, [$item]);
然后将

$item插入$newItems[$index]