使用来自MYSQL

时间:2016-09-01 09:51:49

标签: php mysql json google-visualization

我的最终目标是获得一个图表,显示多个折线图(取决于存在的年数),所有月份显示在X轴上,数量显示在Y轴上。这是我见过的最接近我想要达到的目标:

google line chart

上图显示了我想要实现的目标。如前所述,X轴上的月份与Y轴上的量相同。然后'值'将是从查询返回的年份,即每年将有自己的折线图

这是返回json的php位:

<?php
    $results = array('cols' => array (array('label' => 'Date', 'type' => date'),
               array('label' => 'Amount', 'type' => 'number')
               ),
               'rows' => array()
              );

    $query = $db->prepare('SELECT * FROM Claims GROUP BY EXTRACT(MONTH FROM ClaimDate ) , EXTRACT( YEAR FROM ClaimDate ) ');

    $query->execute();
    $rows1 = $query->fetchAll(PDO::FETCH_ASSOC);

    foreach($rows1 as $row)
    {
        $ClaimDate = DateTime::createFromFormat('Y-m-d H:i:s', $row['ClaimDate'])->format('Y-m-d');

        $dateArr = explode('-', $ClaimDate);
        $year = (int) $dateArr[0];
        $month = (int) $dateArr[1] - 1; 
        $day = (int) $dateArr[2];

        $results['rows'][] = array('c' => array(array('v' => "Date($year, $month, $day)"), array('v' => $row['amount'])
        ));
    }
    $json = json_encode($results, JSON_NUMERIC_CHECK);
    // print_r($json);exit;
?>

这是json返回的:

{"cols":[{"label":"Date","type":"date"},{"label":"Amount","type":"number"}],"rows":[{"c":[{"v":"Date(2015, 5, 23)"},{"v":6000}]},{"c":[{"v":"Date(2016, 5, 23)"},{"v":16000}]},{"c":[{"v":"Date(2015, 6, 23)"},{"v":10000}]},{"c":[{"v":"Date(2016, 6, 23)"},{"v":10000}]},{"c":[{"v":"Date(2015, 7, 23)"},{"v":5000}]},{"c":[{"v":"Date(2016, 7, 23)"},{"v":60000}]}]}

最后,这是呈现图表的功能:

<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"]});
google.setOnLoadCallback(drawChart);

function drawChart() 
{
   var data = new google.visualization.DataTable(<?php echo json_encode($json); ?>);
   var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
   chart.draw(data, {width: 400, height: 240});
}   
</script>
<div id="line_chart"></div>

所有这些的输出如下:

chart rendered by the above code

如上图所示,我与实现我想要的东西相距甚远。我坚持这一点,任何帮助将不胜感激

修改

根据Ram Kannan Raj的回答,我已将 ORDER BY ClaimDate ASC 添加到我的查询中,折线图确实看起来更具代表性:

improved linechart

但仍然不是我想要的输出。每年应该有自己的折线图,X轴是所有月份

2 个答案:

答案 0 :(得分:1)

使用您的查询以Asc顺序尝试ClaimDate

$query = $db->prepare('SELECT * FROM Claims GROUP BY EXTRACT(MONTH FROM ClaimDate ) , EXTRACT( YEAR FROM ClaimDate ) ORDER BY ClaimDate ASC');

答案 1 :(得分:0)

为了获得您描述的图表...

1)每年单独的行需要为每个单独的列(系列) 2)跨越hAxis的所有月份都需要离散轴(字符串值)
3)图表也需要足够宽以显示所有标签

按如下方式生成DataTable,包含12行,每月一行

{
  "cols":[
    {"label":"Month","type":"string"},
    {"label":"2014","type":"number"},
    {"label":"2015","type":"number"},
    {"label":"2016","type":"number"}
  ],
  "rows":[
    {"c":[{"v":"January"},{"v":1000},{"v":1200},{"v":1400}]},
    {"c":[{"v":"February"},{"v":1600},{"v":1800},{"v":2000}]},
    {"c":[{"v":"March"},{"v":2200},{"v":2400},{"v":2600}]},
    ...
  ]
}

动态创建,请参阅以下php中的注释

<?php
    $query = $db->prepare('SELECT * FROM Claims GROUP BY EXTRACT(MONTH FROM ClaimDate ) , EXTRACT( YEAR FROM ClaimDate ) ORDER BY ClaimDate ASC');

    $query->execute();
    $rows1 = $query->fetchAll(PDO::FETCH_ASSOC);

    $dates = array();

    // create data table with initial month column
    $results = array(
      'cols' => array(
        array('label' => 'Month', 'type' => 'string')
      ),
      'rows' => array()
    );

    // create a column for each year in the data
    $colYear = "";
    foreach($rows1 as $row) {
      $year = DateTime::createFromFormat('Y-m-d H:i:s', $row['ClaimDate'])->format('Y');
      $year = strval($year);

      if ($year != $colYear) {
        $results['cols'][] = array('label' => $year, 'type' => 'number');
        $colYear = $year;
      }
    }

    // create hAxis ticks
    $hTicks = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');

    // create 12 blank rows for each month
    $chartRows = array();
    foreach($hTicks as $hMonth) {
      $blankRow = array(array('v' => $hMonth));
      for ($x = 1; $x < count($results['cols']); ++$x) {
        $blankRow[] = array('v' => null);
      }
      $chartRows[] = array('c' => $blankRow);
    }

    // fill in the rows from the data
    foreach($rows1 as $row) {
      // get year and month for current row
      $year = DateTime::createFromFormat('Y-m-d H:i:s', $row['ClaimDate'])->format('Y');
      $month = DateTime::createFromFormat('Y-m-d H:i:s', $row['ClaimDate'])->format('F');
      $colYear = strval($year);

      // find month row
      for ($i = 0; $i < count($hTicks); ++$i) {
        if ($hTicks[$i] == $month) {
          // find year column
          for ($x = 0; $x < count($results['cols']); ++$x) {
            if ($results['cols'][$x]['label'] == $colYear) {
              $chartRows[$i]['c'][$x]['v'] = $row['amount'];
            }
          }
        }
      }
    }

    $results['rows'] = $chartRows;

    $json = json_encode($results);

?>

和客户端......

请注意hAxis.ticks的选项 并删除了width

的选项
<script src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"]});
google.setOnLoadCallback(drawChart);

function drawChart()
{
  var data = new google.visualization.DataTable(<?php echo json_encode($json); ?>);
    var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
    chart.draw(data, {
      hAxis: {
        ticks: <?php echo json_encode($hTicks); ?>
      },
      height: 400
    });
}
</script>
<div id="line_chart"></div>