1

Note: This is a follow-up question to an earlier post of mine.

I have a PHP array which I need to parse to a JavaScript. Currently I am attempting to do so, using <?php echo json_encode($array_name)?> inside the JavaScript. For most of the data in the array, this works fine, except for the dates. The array I am trying to parse looks like this:

$timeData = array(
  array('1', 'Some task',        date('2015-04-09'), date('2015-04-23')),
  array('2', 'Another task',     date('2015-04-13'), date('2015-04-20')),
  array('3', 'A different task', date('2015-04-16'), date('2015-04-30))
);
?>

I need to parse this array, in a way that makes it usable in Google Charts Timeline, where the function looks like this (see comment in code):

<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization',
       'version':'1','packages':['timeline']}]}"></script>
<script type="text/javascript">

google.setOnLoadCallback(drawChart);
function drawChart() {
  var container = document.getElementById('example2.1');
  var chart = new google.visualization.Timeline(container);
  var dataTable = new google.visualization.DataTable();

  dataTable.addColumn({ type: 'string', id: 'Term' });
  dataTable.addColumn({ type: 'string', id: 'Name' });
  dataTable.addColumn({ type: 'date', id: 'Start' });
  dataTable.addColumn({ type: 'date', id: 'End' });

  // This is the part I would like to replace with the PHP array
  dataTable.addRows([
    [ '1', 'George Washington', new Date(1789, 3, 29), new Date(1797, 2, 3) ],
    [ '2', 'John Adams',        new Date(1797, 2, 3),  new Date(1801, 2, 3) ],
    [ '3', 'Thomas Jefferson',  new Date(1801, 2, 3),  new Date(1809, 2, 3) ]]);

  chart.draw(dataTable);
}
</script>

I have tried several different ways of creating the dates in the PHP array, including new Date() and new DateTime(), all without luck. My final resort is to split the array up into pieces, before parsing the data. However this seems somewhat silly, as it is to be put together as an array again inside the JavaScript. Is there any way to write the dates in the PHP array, so that they work when parsed into the JavaScript?

Community
  • 1
  • 1
Jakob Busk Sørensen
  • 5,599
  • 7
  • 44
  • 96
  • Have a look at this question : https://stackoverflow.com/questions/9755911/send-php-date-to-javascript-date-format – Fifi Jun 15 '18 at 07:57
  • The solution which works is in the answer - https://stackoverflow.com/questions/36233412/using-timeline-google-chart-api-in-php-date-time-formatting-issues/36238497#36238497 – Sharunas Bielskis Sep 01 '20 at 17:47

3 Answers3

1

In the PHP side you can return the timestamp so it is easier to handle in JavaScript:

<?php    
$timeData = array(
    array('1', 'Some task',        DateTime::createFromFormat('Y-m-d', date('2015-04-09'))->format('U')*1000, DateTime::createFromFormat('Y-m-d', date('2015-04-23'))->format('U')*1000,
    array('2', 'Another task',     DateTime::createFromFormat('Y-m-d', date('2015-04-09'))->format('U')*1000, DateTime::createFromFormat('Y-m-d', date('2015-04-20'))->format('U')*1000,
    array('3', 'A different task', DateTime::createFromFormat('Y-m-d', date('2015-04-16'))->format('U')*1000, DateTime::createFromFormat('Y-m-d', date('2015-04-30'))->format('U')*1000
);
?>

For the JavaScript part you can then walk the result to append the rows:

/* Assuming rows contains a valid JS array with dates expressed as timestamps in milliseconds
    rows = [
        [1, "Some task", 1428570428000, 1429780165000],
        [2, "Another task", 1428570428000, 1429520977000],
        [3, "A different task", 1429175344000, 1430384993000]
    ];
*/
for (var i = 0; i < rows.length; i++) {
    dataTable.addRow(
        rows[i][0],
        rows[i][1],
        new Date(rows[i][2]),
        new Date(rows[i][3]),
    );
}

It is also possible to send the date as string according Google's documentation Dates and Times Using the Date String Representation. So you can also return this from PHP (note that in JS the months are zero indexed):

<?php    
$timeData = array(
    array('1', 'Some task',        "Date(2015, 3, 9, 0, 0, 0, 0)", "Date(2015, 3, 23, 0, 0, 0, 0)",
    array('2', 'Another task',     "Date(2015, 3, 9, 0, 0, 0, 0)", "Date(2015, 3, 20, 0, 0, 0, 0)",
    array('3', 'A different task', "Date(2015, 3, 16, 0, 0, 0, 0)", "Date(2015, 3, 30, 0, 0, 0, 0)"
);
?>

And in JS simply do this:

/* Assuming rows contains a valid JS array with dates expressed as strings
    rows = [
        [1, "Some task", "Date(2015, 3, 9, 0, 0, 0, 0)", "Date(2015, 3, 23, 0, 0, 0, 0)"],
        [2, "Another task", "Date(2015, 3, 9, 0, 0, 0, 0)", "Date(2015, 3, 20, 0, 0, 0, 0)"],
        [3, "A different task", "Date(2015, 3, 16, 0, 0, 0, 0)", "Date(2015, 3, 30, 0, 0, 0, 0)"]
    ];
*/
dataTable.addRows(rows);
Josué
  • 120
  • 4
  • Exactly what is `rows` in this case? I can't figure out how to get from `$timeData` to `rows`..? Man, I suck at this :-/ – Jakob Busk Sørensen Mar 12 '15 at 09:47
  • That Google link seems promising, now I just need to figure out how to put that to use :-) – Jakob Busk Sørensen Mar 12 '15 at 10:11
  • 1
    rows is the array you got from PHP, but now in JS. I'm assuming you're using AJAX to get the response from PHP and then execute the callback to render the chart, perhaps you're doing differently. I have updated the code to show the expected result from PHP and the value for rows variable in JS for each case. Hope it helps. – Josué Mar 12 '15 at 10:16
  • Not using AJAX at the moment, but I am beginning to think that I might have to... – Jakob Busk Sørensen Mar 13 '15 at 10:08
  • It is not mandatory that you use AJAX. You can print the JSON contents into the JavaScript if this is embedded into the same php page by just adding the php tags and printing the JSON result, so in the JS part, before `dataTable.addRows(rows)`, you can do something like this `var rows = ;`. That should return the desired array structure into the `rows` variable and should make your scripts work. – Josué Mar 14 '15 at 23:47
  • Regarding my previous comment, please note this is good as a start, but I don't recommend it, as if for any reason (bug, issue, etc.) PHP cannot return the `$timeData` variable as a valid JSON object, then your JS code might break. So a cleaner approach could be to use AJAX to keep the server and client separated and handle the success and error cases accordingly. – Josué Mar 14 '15 at 23:50
0

you cannot pass this format to Date constructor. Try in this way:

var parts = mydate.split('-');
var mydateparsed = new Date(parts[0],parts[1],parts[2]);

Hope it will be usefully for you.

Regards

manuelbcd
  • 3,106
  • 1
  • 26
  • 39
  • Would it be easier to load the data from the database, directly in JavaScript? As far as I understand this should be possible, however a bit more troublesome than PHP. – Jakob Busk Sørensen Mar 12 '15 at 08:19
  • could you explain this question please? I'm not sure of understand you – manuelbcd Mar 12 '15 at 08:45
  • What I meant was that I read somewhere that you can connect to a MySQL database using something called AJAX. Then maybe, using that, it would be possible to create the table inside the JavaScript, rather than converting it from PHP – Jakob Busk Sørensen Mar 12 '15 at 09:06
  • 1
    Ok I understand. You have both implementation options: PHP or AJAX. - In PHP it is easiest but not dynamic from client side perspective. - In AJAX is a little bit more difficult if you are a beginner. Also you can try. Wrap values into JSON structure and serve it to client through AJAX connection. – manuelbcd Mar 12 '15 at 09:20
0

I created a loop in jQuery that convert each date into a JS date after converting the array with json_encode:

<?php "var timeData = " . json_encode($timeData) . ";\n"; ?>
$.each( timeData, function ( index, value )
{
    timeData[index]['2'] = new Date(value['2']);
    timeData[index]['3'] = new Date(value['3']);
})

Note that this solution is processed on client side (it relieves the server).

Fifi
  • 3,360
  • 2
  • 27
  • 53