Created
December 6, 2022 01:51
-
-
Save TWithers/883346d6297d41f791ff11342eaaff84 to your computer and use it in GitHub Desktop.
Laravel - 2D Array to CSV string
This file contains hidden or 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
function arrayToCsv(array $data) { | |
retun collect($data) // turn into collection | |
->map(fn ($i) => collect($i)) // turn next layer into collection | |
->pipe(fn ($c) => $c->prepend($c->first()->keys())->map->values()) //grab keys from firt item in the array and prepend them and return only the array values | |
->pipe(function($c){ // format fields for CSV: escape " with another ", wrap fields with new lines, commas, and double quotes with a quote | |
return $c->map->map(function($i){ | |
if(Str::contains($i,'"')) { | |
return '"'.str_replace('"', '""', $i).'"'; | |
} elseif (Str::contains($i,[',',"\n"])){ | |
return '"'.$i.'"'; | |
} | |
return $i; | |
}); | |
}) | |
->map->implode(',') // join inner items with a comma | |
->implode("\n"); // join outer items with a new line | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment