谷歌图表 + MySQL/json

Posted

技术标签:

【中文标题】谷歌图表 + MySQL/json【英文标题】:GoogleCharts + MySQL/json 【发布时间】:2013-06-01 18:21:27 【问题描述】:

我这几天一直在努力让它工作。我想要的是用 googlecharts 创建列/条形图。并从我的数据库中动态生成。

我的查询:

SELECT gs.league as league
             , (Select Count(*) From gamestats WHERE season=gs.season AND league=gs.league AND event=1) as one
             , (Select Count(*) From gamestats WHERE season=gs.season AND league=gs.league AND event=2) as two
             , (Select Count(*) From gamestats WHERE season=gs.season AND league=gs.league AND event=3) as three
             , (Select Count(*) From gamestats WHERE season=gs.season AND league=gs.league AND event=4) as four
             , (Select Count(*) From gamestats WHERE season=gs.season AND league=gs.league AND event=5) as five
             , (Select Count(*) From gamestats WHERE season=gs.season AND league=gs.league AND event=6) as six
           FROM gamestats gs WHERE gs.season=2013 AND gs.league < 3 GROUP by gs.league

如果我只是尝试 json_encode($result) 它会给我错误的 json 格式。这就是我现在得到的:

["league":"2","one":"9","two":"3","three":"9","four":"2","five":"8","six":"12","league":"4","one":"1","two":"0","three":"0","four":"1","five":"1","six":"2"]

这不会产生任何东西。在 GoogleChart 示例中,json 是这样的:


"cols": [
  "id":"","label":"Topping","pattern":"","type":"string",
    "id":"","label":"Slices","pattern":"","type":"number"
  ],
  "rows": [
    "c":["v":"Mushrooms","f":null,"v":3,"f":null],
    "c":["v":"Onions","f":null,"v":1,"f":null],
    "c":["v":"Olives","f":null,"v":1,"f":null],
    "c":["v":"Zucchini","f":null,"v":1,"f":null],
    "c":["v":"Pepperoni","f":null,"v":2,"f":null]
  ]

如何从我的查询中获取这种 json 格式?谢谢!

【问题讨论】:

【参考方案1】:

前段时间我也为此苦苦挣扎。这是我修复它的方法,我想你会明白的。

$data = $this->stats_model->get_flights_data(); // this is the model

$label = array();

array_push($label, array("id" => "", "label" => "Airline", "pattern" => "", "type" => "string"));
array_push($label, array("id" => "", "label" => "Amount", "pattern" => "", "type" => "number"));

$rows = array();
foreach($data as $result) 
    array_push($rows, array("c" => array(array("v" => $result['airline'], "f" => null), array("v" => (int)$result['amount'], "f" => null ))));


$cols = array("cols" => $label, "rows" => $rows);
echo json_encode($cols);

这是我的模型:

$query = "SELECT count(flight_number) AS `amount`, airline from flights_database WHERE flight_date = CURDATE() AND airline != '' GROUP by airline HAVING count(flight_number)>0 ORDER by count(flight_number) DESC, airline DESC LIMIT 10";

$q = $this->db->query($query);
$data = $q->result_array();

return $data;

希望这能给你一些见解!

【讨论】:

哇,谢谢!现在我可以显示图表了。但是现在有一些新问题.. dl.dropboxusercontent.com/u/62375224/chart.png 您需要创建另一个标签,并且还要在array_push的末尾添加另一个数组,例如array("v" =&gt; (int)$result['amount'], "f" =&gt; null ) 好的,这是有道理的,愚蠢的我..再次感谢!现在一切正常:)

以上是关于谷歌图表 + MySQL/json的主要内容,如果未能解决你的问题,请参考以下文章

可以在 Extjs4 图表中制作谷歌图表

没有得到谷歌图表和amcharts4之间相同的图表

谷歌图表图例重叠

谷歌图表在弃用后复合图表

如何动态添加新的图表类型到谷歌烛台图表

如何在一页上添加两个谷歌图表?