我在try 使用GROUP BY创建嵌套的多对象json数组时遇到困难 birth_place在我的REST API应用程序中,这是我在控制器中的代码:
$db = db_connect();
$data = [
'status' => true,
'error' => null,
'data' => $db->query('SELECT birth_place, COUNT(id) as jumlah_data_user, GROUP_CONCAT(id) as id, GROUP_CONCAT(name) as name, GROUP_CONCAT(birth_date) as birth_date, GROUP_CONCAT(gender) as gender FROM users GROUP BY birth_place')->getResultArray()
];
return $this->respond($data, 200);
这就是我的结果,数据被成功地分组,但组合的数据没有被分成多维数组,使用CREATE NEW TITLE AS USERS,而是变成了组合的字符串.
"status": true,
"error": null,
"data": [
{
"birth_place": "Administrasi Jakarta Barat",
"jumlah_data_user": "3",
"id": "716,764,922",
"name": "Elvina Nuraini,Rina Kezia Novitasari,Viktor Firmansyah M.Pd",
"birth_date": "1975-08-28,1988-06-07,1989-05-13",
"gender": "female,female,male"
},
{
"birth_place": "Administrasi Jakarta Pusat",
"jumlah_data_user": "2",
"id": "993,866",
"name": "Mursinin Banawa Marbun M.Pd,Ibrahim Gunawan",
"birth_date": "1991-12-27,1995-01-01",
"gender": "male,male"
},
];
这是我在项目运行时预期的结果:
"status": true,
"error": null,
"data": [
{
"birth_place" : "Administrasi Jakarta Barat",
"jumlah_data_user" : 3,
"users": [
{
"id": 716,
"name": "Elvina Nuraini",
"birth_date": "1975-08-28",
"gender": "female"
},
{
"id": 764,
"name": "Rina Kezia Novitasari",
"birth_date": "1988-06-07",
"gender": "female"
},
{
"id": 922,
"name": "Viktor Firmansyah M.Pd",
"birth_date": "1989-05-13",
"gender": "male"
}
]
},
{
"birth_place": "Administrasi Jakarta Pusat",
"jumlah_data_user" : 2,
"users": [
{
"id": 993,
"name": "Mursinin Banawa Marbun M.Pd",
"birth_date": "1991-12-27",
"gender": "male"
},
{
"id": 866,
"name": "Ibrahim Gunawan",
"birth_date": "1995-01-01",
"gender": "male"
}
]
},
];
如何做到这一点?