【问题标题】:Laravel 5.2 Push onto deeper indexed arrays within a CollectionLaravel 5.2 推送到集合中更深的索引数组
【发布时间】:2016-08-25 15:48:26
【问题描述】:

有没有一种方法可以在不先将集合转换为数组的情况下,对集合上更深的索引进行更改/合并?

我有一个包含 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);

【问题讨论】:

    标签: laravel laravel-5 laravel-5.2 laravel-collection


    【解决方案1】:

    由于集合实现了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]));
    

    【讨论】:

    • 谢谢,我不知道 :) 我有一些错误,最初提到 $collection 是一个对象,所以我只是假设我不能像数组一样访问它
    • 当我尝试使用 array_push [2016-08-24 16:40:03] local.ERROR: ErrorException: array_push() expects parameter 1 to be array, object given in /home/vagrant/project/app/Http/Controllers/EventController.php:282 Stack trace: #0 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'array_push() ex...', '/home/vagrant/s...', 282, Array) #1 /home/vagrant/project/app/Http/Controllers/EventController.php(282): array_push(Object(Illuminate\Database\Eloquent\Collection), Object(Illuminate\Database\Eloquent\Collection)) 时,我似乎仍然收到该错误
    • 很好,这是一个非常干净的解决方案。谢谢
    • 唯一的问题是 array_merge 不喜欢 $collection[$index] 它说它不是一个数组 - [2016-08-25 16:52:48] local.ERROR: ErrorException: array_merge(): Argument #1 is not an array in /home/vagrant/project/app/Http/Controllers/EventController.php:334
    【解决方案2】:

    我在上面临时使用 array_push 提出的解决方案没有将数组与现有数组合并,但这确实有效并且看起来更优雅一些。感谢 Marcin Nabialek 指出 Collections 实现了 ArrayAccess 接口,该接口并没有解决 array_push 的使用,而是在下面的答案中用于通过更改覆盖现有数组。

    $collection[$index] = collect($collection->get($key))->merge($array);
    

    我愿意接受任何改进以推动我对 Collections 的使用。

    【讨论】:

      【解决方案3】:

      使用put 非常简单

      $collection->put($index, $array);

      就是这样

      如果你想推到收集结束使用push

      $collection->push($array);

      【讨论】:

        猜你喜欢
        • 2018-09-23
        • 2021-09-21
        • 2016-04-09
        • 2019-02-10
        • 1970-01-01
        • 2018-01-16
        • 1970-01-01
        • 1970-01-01
        • 2016-03-23
        相关资源
        最近更新 更多