Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel map continue

Tags:

php

laravel

How I can in laravel map function continue loop?

I have code:

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;
        }
});

And output:

Collection {#986 ▼
   #items: array:4 [▼
     0 => false
     1 => false
     2 => array:1 [▶]
     3 => array:1 [▶]
    ]
}

I don't need params with false, I need continue it or delete. How I can resolve this?

like image 484
Dumitru Avatar asked Dec 30 '18 10:12

Dumitru


1 Answers

You can add a reject function after the map to remove all values that are 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;
    });
like image 126
Jerodev Avatar answered Oct 09 '22 20:10

Jerodev