我需要使用highcharts创建basic column chart。这是我的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
(选民与非选民)作为我的系列和label
(东部与西部)作为我的xAxis的正确数据格式应该是(请参阅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
)
有人会提供一些提示吗?我真的很感激!!
答案 0 :(得分:1)
您可以尝试:
$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))
{
if (!in_array($row['label'], $response['xlabels']))
{
$response['xlabels'][] = $row['label'];
}
$response['xdata'][ $row['kpi'] ][] = (float)$row['val'];
}
pg_free_result($result);
pg_close($db);
第一个变化:
if (!in_array($row['label'], $response['xlabels']))
{
$response['xlabels'][] = $row['label'];
}
避免将“East”和“West”多次保存到xlabels数组中。
第二个变化:
$response['xdata'][ $row['kpi'] ][] = (float)$row['val'];
将向xdata数组添加维度:根据“kpi”将值分配给不同的数组。