[英]How can I add an item into a Laravel Eloquent Collection by index?
我嘗試了以下但它不起作用。
$index = 2;
$collection->put($index, $item4);
例如,如果$ collection看起來像這樣:
$collection = [$item1, $item2, $item3];
我想最終得到:
$collection = [$item1, $item2, $item4, $item3];
最簡單的方法可能是拼接它,如下所示:
$collection->splice(2, 0, [$item4]);
集合通常支持與常規PHP數組相同的功能。 在這種情況下,它是在幕后使用的array_splice()函數。
通過將第二個參數設置為0,您實質上告訴PHP“轉到數組中的索引2,然后刪除0個元素,然后插入我剛才提供的元素”。
詳細闡述喬爾的答案:
splice
修改原始集合並返回提取的元素 然后在索引$index
處添加$item
:
$collection->splice($index, 0, [$item]);
或一般:
$elements = $collection->splice($index, $number, [$item1, $item2, ...]);
其中$number
是我們要從原始集合中提取(和刪除)的元素數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.