有没有一种方法可以将更改放入/合并到集合上更深的索引,而无需先将集合转换为数组?
我有一个包含 4 个索引的 $collection,它们都包含 $arrays,所以为了推送到数组,我必须这样做:
$collection = $collection->toArray(); // without this get array_push parameter 1 should be an array object given error
array_push($collection[$index], $array);
但是,我希望有更好的方法,这样我就不必在继续之前重新收集(...)原始的 $collection ,如下所示,我知道这是行不通的,但形成了一个例子比上面更不尴尬的事情:
$collection->get($index)->merge($array);
作为集合实现
ArrayAccess
接口,而不是:
$collection = $collection->toArray();
array_push($collection[$index], $array);
您可以使用:
array_push($collection[$index], $array);
编辑
好吧,代码将无法工作,因为您收到无法分配重载属性的错误,但您在评论中还提到了其他错误。
假设你有这样的收藏:
$collection = collect([[1,2],[11,12],[21,22],[31,32]]);
并且您想将
13
附加到 [11,12]
。
你可以这样做:
$collection->put(1, array_merge($collection[1], [13]));
我临时使用上面的 array_push 提出的解决方案没有将数组与现有数组合并,但这确实有效并且看起来更优雅。感谢 Marcin Nabialek 指出 Collections 实现了 ArrayAccess 接口,该接口没有解决 array_push 的使用,但在下面的答案中用于通过更改覆盖现有数组。
$collection[$index] = collect($collection->get($key))->merge($array);
我愿意接受任何改进以推动我对 Collections 的使用。