简体   繁体   中英

PHP date() to JavaScript new Data() - Inside array

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?

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);

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM