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

如何用PHP从MySQL关联表生成嵌套JSON结构

解决方案:生成嵌套JSON结构

要把扁平的查询结果转换成你想要的嵌套结构,核心是将同一分类下的引用分组,而不是直接把每一行都push到数组里。我们可以通过遍历查询结果时维护一个分类映射来实现这个需求。

修改后的PHP代码

<?php
$host = 'localhost';
$user = 'root';
$pwd = 'root';
$db = 'demoqouteapp';
$conn = mysqli_connect($host, $user, $pwd, $db);

if (!$conn) {
    die("Error in connection:" . mysqli_connect_error());
}

$response = array();
$sql_query = "select c.cat_names, q.Qoutes from categories AS c inner join `qoute` as q on c.id = q.id";
$result = mysqli_query($conn, $sql_query);

if (mysqli_num_rows($result) > 0) {
    // 用一个临时数组来按分类分组引用
    $categoryMap = array();
    
    while ($row = mysqli_fetch_assoc($result)) {
        $catName = $row['cat_names'];
        $quoteText = $row['Qoutes'];
        
        // 检查当前分类是否已经在映射中
        if (!isset($categoryMap[$catName])) {
            // 分类不存在,初始化条目
            $categoryMap[$catName] = array(
                'cat_names' => $catName,
                'qoutes' => array()
            );
        }
        
        // 将当前引用添加到对应分类的列表中
        array_push($categoryMap[$catName]['qoutes'], array(
            'qoutes' => $quoteText
        ));
    }
    
    // 将映射中的值转换为最终的数组格式
    $response = array_values($categoryMap);
} else {
    $response['success'] = 0;
    $response['message'] = 'No data';
}

echo json_encode($response);
mysqli_close($conn);
?>

关键逻辑说明

  1. 分类映射数组:$categoryMap用分类名称作为键,这样可以快速判断当前分类是否已经被处理过,避免重复创建分类条目。
  2. 分组处理:每遍历一行结果时,先检查分类是否存在于映射中:
    • 如果不存在,就创建一个包含cat_names和空qoutes数组的结构。
    • 如果存在,直接把当前引用对象追加到该分类的qoutes数组里。
  3. 转换为最终数组:最后用array_values($categoryMap)把映射的键去掉,只保留值数组,这样就得到了你想要的嵌套JSON结构。

预期输出示例

运行修改后的代码,你会得到类似这样的JSON:

[
    {
        "cat_names": "Animal",
        "qoutes": [
            {"qoutes": "this is id 1st text"},
            {"qoutes": "this is 1st id text"}
        ]
    },
    {
        "cat_names": "ball",
        "qoutes": [
            {"qoutes": "this is 2nd id text"},
            {"qoutes": "this is 2nd id text"}
        ]
    },
    {
        "cat_names": "cat",
        "qoutes": [
            {"qoutes": "this is 3rd id text"},
            {"qoutes": "this is 3rd id text"}
        ]
    }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:20:55