Soapbox / laravel-formatter

A Formatter Class for Laravel 4 based on FuelPHP's Formatter Class
249 stars 95 forks source link

How to set CSV title row? #21

Closed ux-engineer closed 9 years ago

ux-engineer commented 9 years ago

Hi,

I have timeseries data like:

[ [ 1417646511,4 ], [ 1417648041,3 ], [ 1417649181,1 ], ...

This exports as CSV without title row – how to add the title row?

0,1
1417646511,4
1417648041,3
1417649181,1
Jaspaul commented 9 years ago

Hi @envision,

To do what you would like to do you would have to used named arrays.

Example,

[ 
  [ 'timestamp' => 1417646511, 'value' => 4 ], 
  [ 'timestamp' => 1417648041, 'value' => 3 ], 
  [ 'timestamp' => 1417649181, 'value' => 1 ], 
  ...

Should output (approx)

timestamp,value
1417646511,4
1417648041,3
1417649181,1
ux-engineer commented 9 years ago

This did it:

$data       = substr_replace($data, '["timestamp","value"],', 1, 0);
$formatter  = Formatter::make($data, Formatter::JSON);
$csv        = $formatter->toCsv();
$csv        = ltrim($csv, "0,1 \r\n");