0

我需要使用 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并保存xdataxAxis.categoriesseries

$.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
    )

有人会给出一些提示如何做到这一点?我真的很感激!!

4

1 回答 1

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”将值分配给不同的数组。

于 2012-09-08T14:48:19.197 回答