【问题标题】:Method for getting items from collection with specific key, value pair and also remove it from original collection in laravel从具有特定键、值对的集合中获取项目并将其从 laravel 中的原始集合中删除的方法
【发布时间】:2019-11-14 07:51:53
【问题描述】:

我正在寻找通过特定键和值获取集合中的项目的方法,我找到了where()

但我也想在从原始集合中获取该项目后将其删除,但我找不到任何可以同时做到这两点的方法。

我见过pull() 方法,但它通过键获取并从集合中删除该列,但我只想删除特定项目。

我查看了collection doc,但找不到任何本地方法,所以我使用 2 方法来实现该需求,代码如下:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);

$filtered_items = $collection->where('price', 100);

$filtered_collection = $collection->whereNotIn('price', [100]);

我认为如果我可以用一种方法完成以上 2 种方法,开销会很小,所以我正在寻找其他解决方案,在此先感谢您的回答。

【问题讨论】:

    标签: laravel laravel-collection


    【解决方案1】:

    你需要这个https://laravel.com/docs/5.5/collections#method-partition

    $collection = collect([
        ['product' => 'Desk', 'price' => 200],
        ['product' => 'Chair', 'price' => 100],
        ['product' => 'Bookcase', 'price' => 150],
        ['product' => 'Door', 'price' => 100],
    ]);
    
    $filtered_items = $collection->where('price', 100);
    
    list($neededCollection, $filteredCollection) = $collection->partition(function ($i) {
        return $i['price'] == 100;
    });
    
    dd($neededCollection, $filteredCollection);
    

    这样的结果

    【讨论】:

    • 你的方法没问题,但我一直在寻找内置方法,但我认为没有类似的方法可用,所以谢谢。
    猜你喜欢
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2010-09-17
    • 2019-02-19
    • 1970-01-01
    相关资源
    最近更新 更多