我有一個包含News項目的集合,我想將對象添加到特定索引。例如:如何在一個集合中插入一個對象在特定索引下的Laravel對象
$item = new NewsItem();
$newsItems->add($item); // to index nr 3
我有一個包含News項目的集合,我想將對象添加到特定索引。例如:如何在一個集合中插入一個對象在特定索引下的Laravel對象
$item = new NewsItem();
$newsItems->add($item); // to index nr 3
這是不可能的。
更好的解決方案是在索引處拼接您的集合,然後創建一個新集合,在索引前複製集合,在您的新項目之前添加,並最終將集合的其餘部分複製到新集合中。
$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
您可以使用拼接在特定的位置插入一個對象:
$newsItems->splice($index, 0, [$item]);
$ item然後將在$ newItems [$ index]