Reputation: 23
I am trying to get some strings from a csv file, to put under a graph from chartjs.
I wrote this php function:
function getTitle($id) {
$stations = fopen("stations.csv", 'r');
//$csv_data = fopen(date("G") . '.csv', 'r');
$csv_data = fopen('16.csv', 'r'); //fopen("/mnt/weather-data/" .
date("Y/m/d/G") . ".csv", 'r');
$data = array();
$DAY_LENGTH = 60 * 60;
$currentDate = date('U');
while (($line = fgetcsv($csv_data)) !== FALSE) {
$date = date('U', strtotime($line[1]));
if ($date >= ($currentDate-$DAY_LENGTH) && $line[2] == $id) {
array_push($data, $line[0]);
}
}
for ($i = 0; $i < count($data); $i++) {
echo $data[$i] . ",";
}
fclose($stations);
fclose($csv_data);
}
which is working fine, everywhere I call this function, it prints the necesarry strings, which is a date, so 2018-02-08 for example.
When I try to call this function in the label part where i need them in ChartJS. it returns this date as a sum, so like 2018-02-08 will return as 2008.
labels: [<?php getTitle(($_GET['id']))?>],
What is it what I'm doing wrong?
Another problem when I try to change $line[0] to $line[1] which is a time with the following format: 20:17:36, my whole application stops working..
Hope anyone can help me!!
Upvotes: 0
Views: 380
Reputation: 382
The Problem with your code is that the echo will just output the content of the variable but as you are parsing it's value into a javascript array you need to surround your value with quotation marks. So if you change
for ($i = 0; $i < count($data); $i++) {
echo $data[$i] . ",";
}
into
for ($i = 0; $i < count($data); $i++) {
echo "'" . $data[$i] . "',";
}
it should work. This will also solve your other problem. So with this change you should also be able to use the time.
Upvotes: 1