doushadu0901 2018-08-13 16:18
浏览 137
已采纳

编写MySQL查询以在PHP中获取数组并输出为JSON

I have the following MySQL Table:

+----+------+-------+--------+-------+-------+
| id | col1 | col2  | col3   | col4  | col5  |
+----+------+-------+--------+-------+-------+
| 1  | a    | Cat A | Joe    | data1 | data2 |
+----+------+-------+--------+-------+-------+
| 2  | a    | Cat A | Carl   | data3 | data4 |
+----+------+-------+--------+-------+-------+
| 3  | b    | Cat B | Mario  | data5 | daa6  |
+----+------+-------+--------+-------+-------+
| 4  | c    | Cat C | Philip | data7 | data8 |
+----+------+-------+--------+-------+-------+

I am building a REST Endpoint and want to output final Result in the following JSON format:

{
  "json_data": {
    "a": [
      {
        "Cat A": [{
            col3:Joe,
            Col4: data1,
            col5: data2
        },{
            col3:Carl,
            Col4: data3,
            col5: data4
        }
    ],
    "b": [
      {
        "Cat B": [{
            col3:Mario,
            Col4: data5,
            col5: data6
        }]
      }
    ],
    "c": [
      {
        "Cat C": [{
            col3:Philip,
            Col4: data7,
            col5: data8
        }]
      }
    ]
  }
}

As you can see from the table and the final JSON output, I want to first group the results by col1 then based on col1 I will group by col2 and eventually show the remaining data.

I am using PHP to create this with the following code:

MYSQL Query: $query = $wpdb->get_results('SELECT * FROM table ORDER BY col2');

PHP Loops & Array:

foreach ($query as $allData) {

        $arrayData2[$allData->col2] = array(
            'col3' => $allData->col3,
            'col4' => $allData->col4,
            'col5' => $allData->col5
        );
    }


    foreach ($query as $col2) {
        $arrayData1[$col2->col2] = array(
            $arrayData2
        );
    }

    foreach ($query as $col1) {
        $array1[$col1->col1] = array(
            $arrayData1,
        );
    }

    return array(
        'json_data' => $array1,
    );

The result is not as expected, can someone please guide me to the error I am doing wrong in order to achieve my expected result.

  • 写回答

2条回答 默认 最新

  • dongsheng4679 2018-08-13 16:37
    关注

    You can achieve your desire result with simple one for loop:

    $resultArray = [];
    foreach ($query as $row) {
        $resultArray[$row->col1][$row->col2][] = ['col3'=>$row->col3, 'col4'=>$row->col4, 'col5'=>$row->col5];
    }
    
    echo json_encode($resultArray);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记