为什么Google图表不适用于此日期格式?

时间:2014-05-08 10:23:03

标签: php sql json

我正在使用PHP和SQL使用Google Charts生成图表。

我有一个特定的图表我已经开始,但Google Charts似乎不喜欢SQL返回的日期格式。

代码

<?php 

include('core/connection.php');

$stid = oci_parse($conn, "     
  SELECT EntryDate AS \"Date\", COUNT(OrderNo) AS \"Orders\"
  FROM Orders
  WHERE EntryDate > '01-MAY-2014'
  AND CustomerNo = 1
  GROUP BY EntryDate
");
oci_execute($stid);

$table = array();
$table['cols'] = array(

    array('label' => 'Date', 'type' => 'date'),
    array('label' => 'Orders', 'type' => 'number')

);

$rows = array();
while($row = oci_fetch_assoc($stid)) {
    $temp = array();

    $date = new \DateTime($row['Date']);            
    $dateStringForGoogleCharts = $date->format("Y/m/d H:i");

    $temp[] = array('v' => (int) $dateStringForGoogleCharts);
    $temp[] = array('v' => (int) $row['Orders']);
    $rows[] = array('c' => $temp);
}

$table['rows'] = $rows;
$jsonTable = json_encode($table);

oci_close($conn);

?>

<html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">

    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {
      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(<?=$jsonTable?>);
      var options = {
          width:  1600,
          height: 800
        };
      // Instantiate and draw our chart, passing in some options.
      // Do not forget to check your div ID
      var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }

    </script>
  </head>

  <body>
    <div id="chart_div"></div>
  </body>
</html>

有人可以使用此代码提供一个示例,说明如何让Google Charts接受此日期格式吗?

更新

我已更新代码,以Google Charts预期的格式生成日期(感谢您的回答),但现在访问该页面时,我在红色框中看到一条错误消息undefined is not a function

1 个答案:

答案 0 :(得分:0)

我使用以下JS成功完成了这项工作:

function drawChart() {
    var data = new google.visualization.DataTable();
    data.addColumn('datetime', 'Date');
    data.addColumn('number', 'Value');
    data.addRows(<?=$json?>);

    var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('chart_div'));
    chart.draw(data, {displayAnnotations: true, colors: ['blue', 'red']});
}

而且,服务器端,在从PHP中获取数据库后,我使用DateTime来格式化JSON的字符串,如下所示:

$date = new \DateTime($row['date']);            
$dateStringForGoogleCharts = $date->format("Y/m/d H:i");

关键位的格式为“Y / m / d H:i” - Google Charts就是这样的。

我的建议是使用DateTime将数据库中的日期格式转换为此格式。我似乎记得一些试验和错误获得API接受的格式,但这种格式肯定有效。