I need to create a basic column chart using highcharts. Here’s my PHP code:
$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);
The PostgreSQL query returns data as follows (campaign_id = 5, for instance):
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
My API saves xlabels and xdata to xAxis.categoriesand 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");
The right data format for kpi (Voter vs. Non-Voter) as my series and label (East vs West) as my xAxis should be (please refer to JSFiddle):
xAxis.categories = ['East', 'West'];
series = [{name: 'Voter',
data: [0.18, 0.82]},
{name: 'Non-Voter',
data: [0.12, 0.88]}]
However my while loop part $response['xlabels'][] = $row['label']; $response['xdata'][] = (float)$row['val']; give me something like this:
[xlabels] => Array
(
[0] => East
[1] => East
[2] => West
[3] => West
)
[xdata] => Array
(
[0] => 0.18
[1] => 0.12
[2] => 0.82
[3] => 0.88
)
Would some one give some hints how to do this? I’d really appreciate it!!
You may try :
The first change :
avoids to save several times “East” and “West” to your xlabels array.
The second change :
Will add a dimension to the xdata array : values are assigned to different arrays according to their “kpi”.