Last active
September 20, 2023 19:03
-
-
Save abdoulmouctard/90e91b74a6b420111c2308492fcff33c to your computer and use it in GitHub Desktop.
Laravel Lazy Collection From CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
LazyCollection::macro("fromCsv", function (string $path, int $chunk = 0, string $separator = ";"): LazyCollection { | |
/** @var LazyCollection $collection */ | |
$collection = static::make(function () use (&$separator, &$path, &$chunk) { | |
$handle = fopen($path, 'r'); | |
while ($line = fgetcsv(stream: $handle, separator: $separator)) { | |
yield array_map(fn ($item) => trim($item), $line); | |
} | |
}); | |
return $chunk > 0 ? $collection->chunk($chunk) : $collection; | |
}); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment