doudun3910 2014-10-18 23:55
浏览 18
已采纳

从PHP中的SQL结果构造一个复杂的JSON对象

I have a db with many tables. One table represents products, one other table represents categories. One product can belong to many categories. So when I request my db to display the products with their categories I of course retrieve many rows as many categories each product has. For instance the result would be

product_name|category      |city
Test1       |cinema        |paris
Test1       |entertainment |paris
Test1       |Other         |paris
Test2       |Food          |new york
Test2       |Restaurant    |new york
Test2       |Night         |new york

What I am trying to do is to create a JSON object using a PHP script for each product name which looks like this :

    [
        {
            "product_name": "Test1",
            "categorie": [
                "cinema",
                "entertainment",
                "Other"
            ],
            "city": "paris"
        },
        {
            "product_name": "Test2",
            "categorie": [
                "Food",
                "Restaurant",
                "Night"
            ],
            "city": "new york"
        }
    ]

When I tried to use json_encode but unsuccessfully I got duplicate rows. thanks for your help

  • 写回答

1条回答 默认 最新

  • dongwen7371 2014-10-19 00:06
    关注

    You will need to reorder your data before the json_encode

    If $rows is the response of your db, you have to go throw

    $data = [];
    foreach($rows as $row) {
        $name = $row['product_name'];
        if(!isset($data[$name])) {
            $data[$name] = [
                'product_name' => $name,
                'city'=>$row['city'],
                'categories'=>[]
            ];
        }
        $data[$name]['categories'][] = $row['category'];
    }
    json_encode(array_values($data)); //this is what you want
    

    Thats it! Maybe you need while ($row=mysqli_fetch_row($result)) instead of foreach, depending on your sql query builder you use. But the idea is the same

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大