Laravel 地图继续

Dum*_*tru 5 php laravel

我如何在 Laravel 地图函数中继续循环?

我有代码:

return collect($response->rows ?? [])->map(function (array $userRow) {
        if ($userRow[0] == 'Returning Visitor') {
            return [
                $userRow[1] => [
                    'type' => $userRow[0],
                    'sessions' => (int) $userRow[2],
                ]
            ];
        } else {
            return false;
        }
});
Run Code Online (Sandbox Code Playgroud)

和输出:

Collection {#986 ?
   #items: array:4 [?
     0 => false
     1 => false
     2 => array:1 [?]
     3 => array:1 [?]
    ]
}
Run Code Online (Sandbox Code Playgroud)

我不需要 params false,我需要继续它或删除它。我该如何解决这个问题?

Jer*_*dev 20

您可以在之后添加一个reject函数map以删除false.

return collect($response->rows ?? [])
    ->map(function (array $userRow) {
        if ($userRow[0] == 'Returning Visitor') {
            return [
                $userRow[1] => [
                    'type' => $userRow[0],
                    'sessions' => (int) $userRow[2],
                ]
            ];
        } else {
            return false;
        }
    })
    ->reject(function ($value) {
        return $value === false;
    });
Run Code Online (Sandbox Code Playgroud)


Avi*_*yan 5

您可以使用filter()or reject()(过滤器的逆)来过滤您的集合,然后根据需要进行映射。像这样的东西:

return collect($response->rows ?? [])->filter(function (array $userRow) {
    return $userRow[0] == 'Returning Visitor';
})->map(function (array $userRow) {
    return [
        $userRow[1] => [
            'type'     => $userRow[0],
            'sessions' => (int) $userRow[2],
        ]
    ];
});
Run Code Online (Sandbox Code Playgroud)