【问题标题】:Laravel remove item from collectionLaravel 从集合中删除项目
【发布时间】:2017-10-19 11:19:43
【问题描述】:

目前我有这个收藏:

return $items->map(function ($item) use ($location, $amount) {
    if($item->is_active) {
        return $this->calculate($item, array_values($location));
    }
 })

当 if 语句为假时,我想从集合中删除该项目。我该怎么做?

已经试过了:

return $items->map(function ($item, $itemKey) use ($location, $amount, $items) {
    if($item->is_active) {
        return $this->calculate($item, array_values($location));
    }

    $items->forget($itemKey);
})

但这不起作用?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    要根据条件从集合中删除项目,您可以使用filterreject 方法。

    您的代码应如下所示:

    return $items->filter(function ($item) {
        return $item->is_active;
    })->map(function ($item) use ($location, $amount, $items) {        
        return $this->calculate($item, array_values($location));
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-19
      • 2013-01-17
      • 2012-12-18
      相关资源
      最近更新 更多