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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?