簡體   English   中英

通過PHP為泡泡圖處理SQL到JSON

[英]Process SQL to JSON through PHP for Bubble Chart

我正在使用Highcharts制作氣泡圖 這是我的數據樣本:

  name  | price | quantity | count
--------+-------+----------+-------
 Female |     2 |        3 |     5
 Female |     3 |       12 |    10
 Female |     5 |        6 |    15
 Female |     1 |        7 |    25
 Male   |     3 |        5 |     7
 Male   |     2 |        9 |    11
 Male   |     5 |        7 |    23
 Male   |     4 |        4 |    14

我正在使用PHP來查詢數據並編碼為JSON:

$query = "SELECT name, price, quantity, count FROM sales WHERE id = $1";

$result = pg_prepare($db, "report", $query);
$result = pg_execute($db, "report", array($ID));

while ($row = pg_fetch_array($result, NULL, PGSQL_ASSOC))
{
        $response['xdata'][$row['name']]['x'][] = $row['price'];
        $response['xdata'][$row['name']]['y'][] = $row['quantity'];
        $response['xdata'][$row['name']]['radius'][] = $row['count'];
}

echo json_encode($response);

但是,為了正確繪制圖形 ,所需的JSON格式如下:

series: [{
    name: 'Female',
    marker:{
        symbol:'circle',
        fillColor:'rgba(24,90,169,.5)',
        lineColor:'rgba(24,90,169,.75)',
        lineWidth:1,
        color:'rgba(24,90,169,1)',
        states:{
            hover:{
                enabled:false
            }
        }
    },
    data: [{x:2,y:3,marker:{radius:5}},
           {x:3,y:12,marker:{radius:10}},
           {x:5,y:6,marker:{radius:15}},
           {x:1,y:7,marker:{radius:25}}]
    },{
    name: 'Male',
    marker:{
        symbol:'circle',
        fillColor:'rgba(238,46,47,.5)',
        lineColor:'rgba(238,46,47,.75)',
        lineWidth:1,
        color:'rgba(238,46,47,1)',
        states:{
            hover:{
                enabled:false
            }
        }
    },
    data: [{x:3,y:5,marker:{radius:7}},
           {x:2,y:9,marker:{radius:11}},
           {x:5,y:7,marker:{radius:23}},
           {x:4,y:4,marker:{radius:14}}]
   }]

我的問題是,如何在PHP中正確處理$query以獲得上述所需的JSON格式,並通過類似optionsBubble.series = data.xdata將其傳遞給series 非常感謝!

您首先必須在PHP結構中構建非db相關的部分,例如

$data = array(
   0 => array(
        'name' => 'Female',
        'marker' => array (
             'symbol': 'circle'
             etc....),
        'data' => array() // database insertion occurs here
        ),
   1 => array(
        'name' => 'Male',
        etc...
        )
);

$locations = array('Female' => 0, 'Male' => 1, etc...) // reverse map your 'name' fields

while(...) {
     $data[$locations[$row['name']]][data]['x'][] = $row['price'];
     $data[$locations[$row['name']]][data]['y'][] = $row['quantity'];
           ^^^^^^^^^^^^^^^^^^^^^^^^--- reverse lookup to get right array index for 'name'
}

首先,我建議您查看一下您的SQL查詢,尤其是WHERE id=$1 如果我沒有弄錯(並且我對此非常肯定。)你的查詢將返回一(1)行並不像你想要的那樣多。 我建議刪除WHERE子句,看看是否能解決您的問題。

如果沒有給我留言,我會看到我看到的其他內容,我們可以從那里開始。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM