3v4l.org

run code in 300+ PHP versions simultaneously
<?php $json_string = '{"error_code":0,"error_message":"","return_data":{"items":[{"id":462,"users":"1,36,38"},{"id":462,"users":"1,4"}]}}'; $res = json_decode($json_string, 1); $items = $res['return_data']['items']; unset($res['return_data']['items']); // unset it first, to replace a new one $new_items = array(); foreach ($items as $key => $item) { $usersArray['id'] = $item['id']; $usersArray['users'] = array(); //create a new Array $usersIdArray = explode(',', $item['users']); foreach ($usersIdArray as $key => $user) { $usersArray['users'][] = array('user_id' => $user); // another level ^ } $res['return_data']['items'][] = $usersArray; } echo json_encode($res, JSON_PRETTY_PRINT);
Output for 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.30, 8.2.0 - 8.2.25, 8.3.0 - 8.3.13
{ "error_code": 0, "error_message": "", "return_data": { "items": [ { "id": 462, "users": [ { "user_id": "1" }, { "user_id": "36" }, { "user_id": "38" } ] }, { "id": 462, "users": [ { "user_id": "1" }, { "user_id": "4" } ] } ] } }

preferences:
81.54 ms | 409 KiB | 5 Q