3v4l.org

run code in 300+ PHP versions simultaneously
<?php $postArray = array ( 0 => array ( 'id' => 1, 'post' => 'hello', 'userId' => 1, 'fileName' => 'hey.jpg', 'time' => 0, ), 1 => array ( 'id' => 1, 'post' => 'hello', 'userId' => 1, 'fileName' => 'test.png', 'time' => 53252354, ), 2 => array ( 'id' => 2, 'post' => 'world', 'userId' => 1, 'fileName' => 'asd.png', 'time' => 0, ), 3 => array ( 'id' => 4, 'post' => 'test', 'userId' => 1, 'fileName' => 'asd2.png', 'time' => 0, ), 4 => array ( 'id' => 3, 'post' => 'ouch', 'userId' => 2, 'fileName' => NULL, 'time' => NULL, ), ); foreach ($postArray as $post) { $fixed_part = array('id' => $post['id'], 'post' => $post['post'], 'userId' => $post['userId']); $key = serialize($fixed_part); if (!isset($out[$key])) $out[$key] = $fixed_part; $out[$key]['attachments'][] = array('fileName' => $post['fileName'], 'time' => $post['time']); } $out = array_values($out); echo json_encode($out, JSON_PRETTY_PRINT);
Output for 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
[ { "id": 1, "post": "hello", "userId": 1, "attachments": [ { "fileName": "hey.jpg", "time": 0 }, { "fileName": "test.png", "time": 53252354 } ] }, { "id": 2, "post": "world", "userId": 1, "attachments": [ { "fileName": "asd.png", "time": 0 } ] }, { "id": 4, "post": "test", "userId": 1, "attachments": [ { "fileName": "asd2.png", "time": 0 } ] }, { "id": 3, "post": "ouch", "userId": 2, "attachments": [ { "fileName": null, "time": null } ] } ]

preferences:
131.17 ms | 410 KiB | 5 Q