PHP 端查詢資料庫 → 組裝陣列 → json_encode() 輸出 → 前端 Highcharts 以 AJAX 取得並渲染。
<?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);
?>
<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);
boost.js 模組或改用 Highcharts Stock。