萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

Highcharts + PHP 動態統計圖表:JSON 資料串接完整範例

資料流向

PHP 端查詢資料庫 → 組裝陣列 → json_encode() 輸出 → 前端 Highcharts 以 AJAX 取得並渲染。

PHP 端資料格式

<?php
header('Content-Type: application/json; charset=utf-8');

// 模擬資料庫查詢結果
$raw = [
    ['region' => '上海', 'value' => 28.2],
    ['region' => '北京', 'value' => 48.2],
    ['region' => '廣東', 'value' => 18.2],
];

// Highcharts 需要的 series 格式
$series = [
    'type' => 'pie',
    'name' => '區域分佈',
    'data' => array_map(
        fn($row) => ['name' => $row['region'], 'y' => (float)$row['value']],
        $raw
    ),
];

echo json_encode(['series' => [$series]], JSON_UNESCAPED_UNICODE);
?>

前端 Highcharts 設定

<div id="chart" style="width:600px;height:400px"></div>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script>
fetch('chart_data.php')
  .then(r => r.json())
  .then(res => {
    Highcharts.chart('chart', {
      chart: {type: 'pie'},
      title: {text: '區域分佈統計'},
      series: res.series
    });
  });
</script>

多序列(多組數據)範例

$series = [];
foreach (['2022','2023','2024'] as $year) {
    $data = [];
    foreach (['上海','北京','廣東'] as $city) {
        $val = getValue($year, $city); // 自行實作查詢
        $data[] = ['name' => $city, 'y' => (float)$val];
    }
    $series[] = ['type' => 'column', 'name' => $year, 'data' => $data];
}
echo json_encode(['series' => $series], JSON_UNESCAPED_UNICODE);

效能優化建議

  • 資料量 > 1k 點:啟用 boost.js 模組或改用 Highcharts Stock。
  • 頻繁查詢:Redis 快取 JSON 字串,TTL 30~300 秒。
  • 大數據匯出:提供 CSV/Excel 下載,避免前端渲染過大資料集。
copyright © 萬盛學電腦網 all rights reserved