Skip to content

Instantly share code, notes, and snippets.

@TWithers
Created December 6, 2022 01:51
Show Gist options
  • Save TWithers/883346d6297d41f791ff11342eaaff84 to your computer and use it in GitHub Desktop.
Save TWithers/883346d6297d41f791ff11342eaaff84 to your computer and use it in GitHub Desktop.
Laravel - 2D Array to CSV string
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