Laravel 集合如何在一个操作器中使用映射和筛选方法?

Laravel 集合如何在一个操作器中使用映射和筛选方法?,laravel,Laravel,在Laravel 6中使用集合是否有一种方法可以在一个Operator中使用映射和过滤方法 我试着说: $dataItems = ItemModel ::getById($id) ->get() ->map(function ($item) { $item['field1'] = 'value1'; $item['field2'] = 'value2'; ... if($co

在Laravel 6中使用集合是否有一种方法可以在一个Operator中使用映射和过滤方法

我试着说:

$dataItems = ItemModel
    ::getById($id)
    ->get()
    ->map(function ($item) {
        $item['field1']  = 'value1';
        $item['field2']  = 'value2';
        ...
        
        if($conditionTrue) {
            return $item;
        }
        return false;
    })
    ->toArray();
但当$conditionTrue为false时,我在结果数组中得到了空元素

我能做吗


谢谢

您可以使用
reduce
方法:

// where $acc is the accumulated value and $curr is the current value in the loop
->reduce(function($acc, $curr) {
    $curr['field1']  = 'value1';
    $curr['field2']  = 'value2';

    if($conditionTrue) {
        $acc[] = $curr;
    }

    return $acc;
}, array());
我想减少的方法就是你想要的。此方法单独完成映射和过滤器的工作


请确保不要调用toArray(),因为如果您确实出于某种原因不想只调用
filter()
,reduce将返回一个数组,这将删除任何与
false
等价的项,在您调用
map(…)
之后,您可以使用您拥有的回调,而将其与
filter
一起使用,由于项目是对象:

->filter(function ($item) {
    $item['field1']  = 'value1';
    $item['field2']  = 'value2';
    ...

    return $condition;
})