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?