3v4l.org

run code in 300+ PHP versions simultaneously
<?php error_reporting(-1); ini_set('display_errors', 1); $json_data = <<<JSON {"messages": [ { "id": 1, "customer": "Dr. Kane Hill", "customer_id": 1, "created_at": "2024-11-19 11:18:57", "text": "Hello, how are you?" }, { "id": 2, "customer": "Dr. Kane Hill", "customer_id": 1, "created_at": "2024-11-19 11:20:57", "text": "I am good, thanks! How about you?" }, { "id": 3, "customer": "Prof. Samir McClure III", "customer_id": 2, "created_at": "2024-11-19 11:21:57", "text": "Hey, what time is it?" }, { "id": 4, "customer": "Prof. Samir McClure III", "customer_id": 2, "created_at": "2024-11-19 11:22:57", "text": "It is 3 PM." }, { "id": 5, "customer": "Shad Leffler", "customer_id": 3, "created_at": "2024-11-19 11:23:57", "text": "Did you finish the project?" }, { "id": 6, "customer": "Shad Leffler", "customer_id": 3, "created_at": "2024-11-19 11:24:57", "text": "New mesh" }, { "id": 7, "customer": "Prof. Samir McClure III", "customer_id": 2, "created_at": "2024-11-19 11:26:57", "text": "Not bed?" }, { "id": 8, "customer": "Prof. Samir McClure III", "customer_id": 2, "created_at": "2024-11-19 11:27:57", "text": "Cool?" } ]} JSON; $messages = json_decode($json_data, true)['messages']; $messages2 = []; $messageCounter = 0; foreach($messages as $row) { $key = $row['customer_id']; if(!isset($messages2[$key])) { $messages2[$key] = [ 'customer' => $row['customer'], 'message_id' => (++$messageCounter), 'customer_id' => $row['customer_id'], 'messages' => [], ]; } $messages2[$key]['messages'][] = [ 'id' => $row['id'], 'created_at' => $row['created_at'], 'text' => $row['text'], ]; } $messages2 = array_values($messages2); echo json_encode($messages2, JSON_PRETTY_PRINT);

preferences:
30.5 ms | 408 KiB | 5 Q