I have a collection with News items and I want to add a object to a specific index. For example:
我有一个带有News Items的集合,我想将一个对象添加到特定的索引中。例如:
$item = new NewsItem();
$newsItems->add($item); // to index nr 3
更多回答
优秀答案推荐
It's not possible.
这不可能。
The better solution is splice your collection at the index, then create a new collection, copy the collection before the index, prepend your new item and, by the end, copy the rest of your collection into the new one.
更好的解决方案是在索引处拼接您的集合,然后创建一个新集合,在索引之前复制该集合,为新项添加前缀,最后将集合的其余部分复制到新的集合中。
$afterIndex = $newsItems->splice($index);
$newItensCollections = $newsItems;
$newItensCollections->prepend($yourNewItem);
$newItensCollections->union($afterIndex);
To splice:
https://laravel.com/docs/master/collections#method-splice
拼接:https://laravel.com/docs/master/collections#method-splice
To prepend:
https://laravel.com/docs/master/collections#method-prepend
添加前缀:https://laravel.com/docs/master/collections#method-prepend
To copy the arrays:
https://laravel.com/docs/master/collections#method-union
要复制阵列,请执行以下操作:https://laravel.com/docs/master/collections#method-union
You can use splice to insert an object at a specific location:
可以使用Splice在特定位置插入对象:
$newsItems->splice($index, 0, [$item]);
$item
will then be inserted in $newItems[$index]
然后,$Item将插入到$newItems[$index]中
If you already have a Collection and want to prepend or push the value in it
如果您已经有一个集合,并且想要预先添加或推送其中的值
$newObject = (object)[
'key_1' => "Value",
'key_2' => "10"
];
$existingCollection->push($newObject);
$existingCollection->prepend($newObject);
更多回答
我是一名优秀的程序员,十分优秀!