You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将PHP多维数组按列转换以适配Google Chart列图表数据格式?

如何将PHP多维数组转换为Google Chart列图表所需格式

需求说明

要构建Google Chart列图表,每列对应一处房产,展示其年度收入:X轴为年份,Y轴为收入金额。需要把给定的PHP多维数组转换成Google Chart要求的JavaScript数组格式。

原始PHP数组

$propertyData = [
    'Property 1' => [
        '2021' => 353.93,
        '2022' => 12628.65,
        '2023' => 12841.57
    ],
    'Property 2' => [
        '2022' => 370.78,
        '2023' => 12841.57
    ]
];

目标Google Chart数据格式

['Year', 'Property 1', 'Property 2'],
['2021', 353.93, 0],
['2022', 12628.65, 370.78],
['2023', 12841.57, 12841.57]

转换实现步骤及代码

  1. 提取并排序所有年份:遍历所有房产的年份数据,收集不重复的年份并按顺序排序,保证X轴年份排列正确。
  2. 构建表头数组:第一个元素固定为'Year',后续依次添加所有房产名称。
  3. 生成年份数据行:对每个年份,依次获取对应房产的收入值,若该年份无数据则填充0(可根据需求改为null)。
  4. 转JSON输出到JS:将处理好的PHP数组转为JSON格式,确保数字类型不被转为字符串,直接传入Google Chart的arrayToDataTable方法。

完整代码示例:

<?php
// 原始房产收入数据
$propertyData = [
    'Property 1' => [
        '2021' => 353.93,
        '2022' => 12628.65,
        '2023' => 12841.57
    ],
    'Property 2' => [
        '2022' => 370.78,
        '2023' => 12841.57
    ]
];

// 提取所有唯一年份并排序
$allYears = [];
foreach ($propertyData as $years) {
    $allYears = array_merge($allYears, array_keys($years));
}
$allYears = array_unique($allYears);
sort($allYears);

// 构建表头
$chartData = [['Year']];
$propertyNames = array_keys($propertyData);
foreach ($propertyNames as $name) {
    $chartData[0][] = $name;
}

// 构建每一行的年份-收入数据
foreach ($allYears as $year) {
    $row = [$year];
    foreach ($propertyNames as $property) {
        // 无数据时填充0,可改为null
        $row[] = $propertyData[$property][$year] ?? 0;
    }
    $chartData[] = $row;
}

// 转为JSON,确保数字类型正确
$jsonChartData = json_encode($chartData, JSON_NUMERIC_CHECK);
?>

<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
    var columnChartData = google.visualization.arrayToDataTable(<?php echo $jsonChartData; ?>);

    var options = {
        title: '房产年度收入统计',
        hAxis: {title: '年份', titleTextStyle: {color: '#333'}},
        vAxis: {minValue: 0, title: '收入金额'},
        chartArea: {width: '70%', height: '60%'}
    };

    var chart = new google.visualization.ColumnChart(document.getElementById('chart_container'));
    chart.draw(columnChartData, options);
}
</script>

<div id="chart_container" style="width: 900px; height: 500px;"></div>

关键说明

  • 使用JSON_NUMERIC_CHECK参数保证收入数值在JSON中以数字类型存在,避免Google Chart解析错误。
  • 用?? 0处理缺失年份的数据,确保每行数据长度一致,也可根据需求替换为null表示无数据。
  • 年份排序后生成的数据行,能保证X轴年份按时间顺序展示。

内容的提问来源于stack exchange,提问作者malteseKnight

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 07:35:11