2

我一直在努力让这个工作好几天了。我想要的是用 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 格式?谢谢!

4

1 回答 1

0

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

$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;

希望这能给你一些见解!

于 2013-06-05T23:01:25.387 回答