如何使用以下代码绘制谷歌折线图?

时间:2013-07-16 07:02:21

标签: php mysql associative-array google-visualization

我想使用“Google Charts”工具绘制折线图。我从MySql数据库中获取折线图所需的数据。它的代码如下:

    <?php
    require_once('../includes/public-application-header.php');
    $con=mysql_connect("localhost","root","eywaadmin") or die("Failed to connect with database!!!!");
  mysql_select_db("OCN", $con); 

    $sql  =" SELECT DATE_FORMAT( FROM_UNIXTIME( transaction_date ) , '%d/%m/%Y') 'transaction_date', COUNT(*) 'total count', SUM(transaction_status = 'success') ";
    $sql .=" success, SUM(transaction_status = 'inprocess') inprocess, SUM(transaction_status = 'fail') fail, ";
    $sql .=" SUM(transaction_status = 'cancelled') cancelled FROM user_transaction WHERE ";
    $sql .=" transaction_date >= 1325376000 AND transaction_date <= 1373846400 GROUP BY date(FROM_UNIXTIME(transaction_date)) ";

    $r= mysql_query($sql) or die(mysql_error()); 
    $transactions = array();
    while($result  = mysql_fetch_array($r, MYSQL_ASSOC)){
      $transactions[] = $result;
    } 
    $rows = array();
      //flag is not needed
      $flag = true;
      $table = array();
      $table['cols'] = array(

    // Labels for your chart, these represent the column titles
    // Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
    array('label' => 'Transaction Date', 'type' => 'string'),
    array('label' => 'Total Count', 'type' => 'number'),
    array('label' => 'Success', 'type' => 'number'),
    array('label' => 'Inprocess', 'type' => 'number'),
    array('label' => 'Failed', 'type' => 'number'),
    array('label' => 'Cancelled', 'type' => 'number'),
    );
  $rows = array();

  foreach($transactions as $tr) {
    $temp = array();

     foreach($tr as $key=>$value){

    // the following line will be used to slice the Pie chart
    $temp[] = array('v' => (string) $key); 

    // Values of each slice
    $temp[] = array('v' => (int) $value);     
    }
  $rows[] = array('c' => $temp); 
}
    $table['rows'] = $rows;

    $jsonTable = json_encode($table);
    //echo $jsonTable;
?>

<html>
    <head>
    <!--Load the Ajax API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.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 = {
          title: 'User Transaction Statistics',
          is3D: 'true',
          width: 800,
          height: 600
        };
      // Instantiate and draw our chart, passing in some options.
      // Do not forget to check your div ID
      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
  </head>
  <body>
    <!--this is the div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

我想把日期(即transaction_date)放在X轴上,将Count值(即10,20,30,40)放在Y轴上。但不幸的是,我没有得到所需格式的折线图。我附上执行上述代码后得到的屏幕截图。

有人可以帮我这方面吗?提前致谢。如果您想了解更多信息,我可以将其添加到问题正文中。 根据{{​​1}}的请求,我发布了为您的参考创建的json响应。如果您仍然需要其他东西,如查询输出等,我可以为您提供。附有线图的屏幕截图。 enter image description here

3 个答案:

答案 0 :(得分:2)

主要问题是您要保存列名以及数据集中的列值。你应该只存储值。

$temp = array();
foreach($tr as $key=>$value){
  // Values of each slice
  $temp[] = array('v' => (int) $value);     
}
$rows[] = array('c' => $temp);                         

第二个问题是您要将所有值转换为整数。如果您希望将日期显示为实际日期,则应该摆脱该转换。

$temp = array();
foreach($tr as $key=>$value){
  // Values of each slice
  $temp[] = array('v' => $value);     
}
$rows[] = array('c' => $temp);                         

答案 1 :(得分:0)

我不知道你的jsonTable是怎样的,但它应该用这种方式格式化:

['transaction date', 'Total count', 'Succes', 'In progress', 'Failed', 'Canceled'],
['19-7-2013', 50, 40, 5, 2, 3],
['20-7-2013', 60, 50, 5, 1, 4],
['21-7-2013', 50, 40, 5, 2, 3],
['22-7-2013', 60, 50, 5, 1, 4],
['23-7-2013', 50, 40, 5, 2, 3]

你能把你的$ jsonTable发给我吗?

此链接显示表格示例:http://jsfiddle.net/kxd2u/

我认为您的数据量不存在问题。我自己制作了一些图表,包含大量数据并且工作正常!

答案 2 :(得分:0)

您输入的数据不正确。试试这个:

foreach ($transactions as $tr) {
    $temp = array();

    $temp[] = array('v' => $tr['transaction_date']);
    $temp[] = array('v' => (int) $tr['total count']);
    $temp[] = array('v' => (int) $tr['success']);
    $temp[] = array('v' => (int) $tr['inprocess']);
    $temp[] = array('v' => (int) $tr['fail']);
    $temp[] = array('v' => (int) $tr['cancelled']);

    $rows[] = array('c' => $temp); 
}

这将生成一个带有离散轴的图表,其中每行数据在图表上均匀分布,无论日期之间的距离如何。如果你想要一个连续的轴(参见this作为离散和连续之间差异的一个例子),你必须对日期的格式有所不同:

列中的

array('label' => 'Transaction Date', 'type' => 'date')
行中的

$dateArray = explode('/', $tr['transaction_date']);
$year = $dateArray[2];
$month = $dateArray[1] - 1; // need to subtract 1 to convert to javascript month format
$day = $dateArray[0];
$temp[] = array('v' => "Date($year, $month, $day)", f: $tr['transaction_date']);

然后,您可以在图表的选项中格式化日期轴:

hAxis: {
    format: 'd/M/yyyy'
}

顺便说一下,你可以在PHP中删除那个$ flag变量 - 它是我在很久以前在Google Visualization API组中作为例子发布的原始代码留下的一个工件。每当代码被复制时,它都会不断出现,而且没有人会删除它。

相关问题