我需要使用 highcharts创建一个基本的柱形图。这是我的 PHP 代码:
$query = "SELECT campaign_id, kpi, label, val FROM table WHERE id = $1";
$result = pg_prepare($db, "report", $query);
$result = pg_execute($db, "report", array($campaignID));
while ($row = pg_fetch_array($result, NULL, PGSQL_ASSOC))
{
$response['xlabels'][] = $row['label'];
$response['xdata'][] = (float)$row['val'];
}
pg_free_result($result);
pg_close($db);
echo json_encode($response);
PostgreSQL 查询返回数据如下(例如,campaign_id = 5):
id | kpi | label | val
----+-----------+-------+------
5 | Voter | East | 0.18
5 | Non-Voter | East | 0.12
5 | Voter | West | 0.82
5 | Non-Voter | West | 0.88
我的 API 保存xlabels
并保存xdata
到xAxis.categories
和series
:
$.get('vote_api.php', {'id' : id}, function(data) {
options.chart.type = 'column';
options.xAxis.categories = data.xlabels;
options.series = data.xdata;
chart = new Highcharts.Chart(options);
}, "json");
kpi
(Voter vs. Non-Voter) 作为我的系列和(East vs West) 作为我的 xAxis的正确数据格式label
应该是(请参阅JSFiddle):
xAxis.categories = ['East', 'West'];
series = [{name: 'Voter',
data: [0.18, 0.82]},
{name: 'Non-Voter',
data: [0.12, 0.88]}]
但是我的while loop
部分$response['xlabels'][] = $row['label']; $response['xdata'][] = (float)$row['val'];
给了我这样的东西:
[xlabels] => Array
(
[0] => East
[1] => East
[2] => West
[3] => West
)
[xdata] => Array
(
[0] => 0.18
[1] => 0.12
[2] => 0.82
[3] => 0.88
)
有人会给出一些提示如何做到这一点?我真的很感激!!