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

PHP中按条件合并数组并生成指定JSON格式的实现问题

解决PHP数组合并与JSON输出的问题

没问题,我来帮你搞定这个模块和章节数组合并、生成指定JSON格式的需求!先梳理下你现有代码的核心问题,再给出修正后的完整方案。

现有代码的核心问题

  1. 循环中每次重置$chapters变量,最后只能保留最后一个模块的章节数据
  2. 没有将章节数据关联到对应的模块对象中
  3. 直接拼接SQL参数存在SQL注入风险,这是必须避免的安全问题
  4. 返回的JSON结构没有合并模块与章节的关联关系

修正后的完整代码

// 获取指定课程下的所有模块数据
$modules = DB::select(
    DB::raw("select unimodules.name as unimodule_name, unimodules.id as module_id from unimodules WHERE course_id = 5 AND unimodules.name IS NOT NULL")
);

// 初始化目标数组,用于存储最终要输出的结构
$targetData = [];

foreach ($modules as $module) {
    // 查询当前模块对应的章节,使用参数绑定避免SQL注入
    $chapters = DB::select(
        DB::raw("select chapters.name as chapter_name from chapters WHERE module_id = ?"),
        [$module->module_id] // 参数自动转义,彻底规避注入风险
    );

    // 将章节数据转换成目标格式:仅保留Chaptername字段
    $formattedChapters = array_map(function($chapter) {
        return ['Chaptername' => $chapter->chapter_name];
    }, $chapters);

    // 组装当前模块的完整结构,添加到目标数组
    $targetData[] = [
        'moduleName' => $module->unimodule_name,
        'chapters' => $formattedChapters
    ];
}

// 返回符合要求的JSON响应
return response()->json([
    'data' => $targetData,
    'message' => 'course_success',
    'status' => 200
]);

关键说明

  • 安全优先:用参数绑定代替直接拼接SQL变量,这是PHP数据库操作的最佳实践,彻底避免SQL注入攻击
  • 关联数据:遍历每个模块时实时查询并绑定对应章节,确保每个模块都能正确关联自己的章节列表
  • 格式适配:通过array_map将章节对象转换成你需要的{Chaptername: "..."}结构,完美匹配目标JSON格式
  • 空章节处理:如果模块没有对应章节,$formattedChapters会自动是空数组,完全符合你的预期输出

最终输出示例

运行后会得到和你期望一致的JSON结构,类似这样:

{
    "data": [
        {
            "moduleName": "Artificial Intelligence",
            "chapters": []
        },
        {
            "moduleName": "Camp",
            "chapters": []
        },
        {
            "moduleName": "Mathematics",
            "chapters": [
                {"Chaptername": "Algebra"},
                {"Chaptername": "Combinatorics"},
                {"Chaptername": "Mathematical physics"},
                {"Chaptername": "Calculus and analysis"}
            ]
        }
    ],
    "message": "course_success",
    "status": 200
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:27:16