Page 1 of 1

String to Array For CSV Writing

Posted: Fri Sep 22, 2017 10:20 pm
by kkonline
Hello All,
I have an array which needs to be converted into CSV format.

2D Array is as below:

I want the 0th element to be replaced by DateTime like
Array
(
[0] => Array
(
[0] => 1 >>Should be replaced by 20170922,09:20:00
[1] => 31.85
[2] => 32.15
[3] => 31.75
[4] => 32.15
[5] => 401352
)

[1] => Array
(
[0] => 2 >> Should be replaced by 20170922,09:25:00
[1] => 31.85
[2] => 32
[3] => 31.75
[4] => 31.85
[5] => 249158
)
)

Since DateTime is a string and this is an array while writing to the file it takes double quotes ( " ) for the string and the output becomes

"20170922,09:20:00",678.6,682.8,677.2,681.75,159294 >> Invalid CSV

I use fputcsv to write the data

Code: Select all

foreach ($data as $fields) {
	fputcsv($fp, $fields);
}
My code, merges array data with string based date

Code: Select all

$data[$i][0]=date('Ymd,H:i:s', $data[0][0] + ($data[$i][0]*300));
$data[0][0]=date('Ymd,H:i:s', $timestamp[0]);
Could you please suggest How could I remove these quotes from the csv
Or
Replace the datetime as an single array value into the existing array

Re: String to Array For CSV Writing

Posted: Sat Sep 23, 2017 3:24 am
by requinix
Are you saying you want the date as the first "column" and the time as the second "column" in the CSV? Because you can't use an unquoted comma in a line without that happening.

Re: String to Array For CSV Writing

Posted: Mon Sep 25, 2017 5:33 pm
by Christopher
You understand that -- by definition -- a value with a comma in it will be quoted in CSV. That's the whole reason for the quotes!

You need to split the field into two fields

Code: Select all

foreach ($data as $i => $fields) {
        $value = $somevalue + ($data[$i][0]*300);     // not sure what this line does, but do some calculation here
	$data[$i][0]=date('H:i:s', $value);                   // add the time
	array_unshift($data[$i], date('Ymd, $value));   // prepend the date and the new 0th element
}
foreach ($data as $fields) {
	fputcsv($fp, $fields);
}

Re: String to Array For CSV Writing

Posted: Tue Sep 26, 2017 2:33 am
by VladSun
http://php.net/manual/en/function.fputcsv.php

Code: Select all

int fputcsv ( resource $handle , array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape_char = "\" ]]] )
enclosure
The optional enclosure parameter sets the field enclosure (one character only).
Default value for $enclosure param is " (i.e. the one that you use by not providing this param)