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

PHP MySQL按月份合并JSON对象实现问题求助

如何在不修改MySQL语句的前提下生成期望的JSON格式?

问题背景

我在生成JSON对象时遇到了问题,期望将各月份对应的Branch及cf值整合到同一数组对象中,但当前输出是每个分支单独一个对象。

期望输出

[{ "month": "Jan", "Branch2": 550965.96 , "Branch1": 663134.44 }, { "month": "Feb", "Branch2": 472793.10, "Branch1": 492784.54 }, { "month": "March", "Branch2": 394616.65, "Branch1": 757639.93 }, { "month": "April", "Branch2": 376403.65 , "Branch1": 569404.61 }]

当前使用的PHP代码

<?php 
$dbhost = 'localhost'; 
$dbname = 'spmdb'; 
$dbuser = 'root'; 
$dbpass = ''; 

try{ 
    $dbcon = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpass); 
    $dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
}catch(PDOException $ex){ 
    die($ex->getMessage()); 
} 

$stmt = $dbcon->prepare("SELECT month.monthname,coll.branch,coll.cf FROM coll INNER JOIN month ON month.id = coll.`month` group by coll.month,coll.branch"); 
$stmt->execute(); 

$row1 = []; 
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) { 
    extract($row); 
    $row1[]= ['month' => $monthname, $branch => $cf]; 
} 

echo json_encode($row1,JSON_NUMERIC_CHECK); 
?>

当前输出结果

[{"month":"Jan","Branch4":40275} ,{"month":"Feb","Branch5":165173.91} ,{"month":"Feb","Branch1":93360.33} ,{"month":"Apr","Branch1":65415.75}]

我想知道能不能在不修改MySQL语句的前提下实现期望的JSON输出?

解决方案

当然可以!你只需要在PHP层面调整数据处理的逻辑,把同一月份的不同分支数据合并到同一个对象里,而不是每次循环都新增独立对象。具体修改如下:

修改后的PHP代码

<?php 
$dbhost = 'localhost'; 
$dbname = 'spmdb'; 
$dbuser = 'root'; 
$dbpass = ''; 

try{ 
    $dbcon = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpass); 
    $dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
}catch(PDOException $ex){ 
    die($ex->getMessage()); 
} 

$stmt = $dbcon->prepare("SELECT month.monthname,coll.branch,coll.cf FROM coll INNER JOIN month ON month.id = coll.`month` group by coll.month,coll.branch"); 
$stmt->execute(); 

// 初始化关联数组,以月份为键存储对应数据
$groupedData = []; 

while($row=$stmt->fetch(PDO::FETCH_ASSOC)) { 
    $month = $row['monthname'];
    $branch = $row['branch'];
    $cf = $row['cf'];
    
    // 若当前月份未在分组数组中,先初始化基础对象
    if (!isset($groupedData[$month])) {
        $groupedData[$month] = ['month' => $month];
    }
    
    // 将当前分支的cf值追加到对应月份的对象中
    $groupedData[$month][$branch] = $cf;
} 

// 把关联数组转为索引数组,匹配期望的JSON结构
$result = array_values($groupedData);

echo json_encode($result,JSON_NUMERIC_CHECK); 
?>

逻辑说明

  1. 用$groupedData关联数组按月份分组,月份名称作为键,能快速判断当前月份是否已有数据;
  2. 循环读取数据库结果时:
    • 若月份不存在,先创建包含month字段的基础对象;
    • 若月份已存在,直接将当前分支的cf值添加到该对象中;
  3. 最后通过array_values()把关联数组转为索引数组,输出的JSON就完全符合你的期望了。

这样修改后,完全不需要改动SQL语句,就能得到目标格式的JSON啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:57:37