目前我有這樣的JSON:[ { "user_id": 6, "room_id": 2, "date_from": "2019-09-15 00:00:00", "date_to": "2020-09-01 00:00:00", "created_at": null, "updated_at": null, "users": [ { "id": 6, "name": "Makenna", "surname": "Boyle", "email": "[email protected]", "university_id": 3 } ], "room": { "id": 2, "room_number": 327, "floor": 3, "slots": 2, "dorm_id": 1, "price": 0, "features": "[{\"feature\":\"Nemokamas WiFi\",\"feature\":\"Erdvus du?as\"}]", "photos": "[{\"img\":\"\\/images\\/rooms\\/9_1_5d3f6735884627.19832875.jpg\"},{\"img\":\"\\/images\\/rooms\\/9_1_5d3f673589a070.51161328.jpg\"},{\"img\":\"\\/images\\/rooms\\/9_1_5d3f67358b0419.09559739.jpg\"}]", "created_at": null, "updated_at": null, "dorm": { "id": 1, "name": "Statybinink? prospekto bendrabutis", "university_id": 2, "photo": "https://www.umt.edu/housing/rh/descriptions/photos/Miller%20West%20Side%20View.jpg", "university": { "id": 2, "name": "Klaip?dos Universitetas", "city": "Klaip?da" } } } }, { "user_id": 8, "room_id": 2, "date_from": "2019-09-15 00:00:00", "date_to": "2020-09-01 00:00:00", "created_at": null, "updated_at": null, "users": [ { "id": 8, "name": "Kassandra", "surname": "Blick", "email": "[email protected]", "university_id": 2 } ],
1 回答

梵蒂岡之花
TA貢獻1900條經驗 獲得超5個贊
此代碼將幫助您實現目標。
$data = json_decode($json);
$newFormat = [];
foreach ($data AS $each) {
if (!isset($newFormat[$each->room_id])) {
$newFormat[$each->room_id] = $each;
} else {
$newFormat[$each->room_id]->users[] = $each->users[0];
}
}
echo "<pre>" . var_export($newFormat, true) . "</pre>";
這將顯示您期望的確切結果
- 1 回答
- 0 關注
- 139 瀏覽
添加回答
舉報
0/150
提交
取消