<?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);
- Output for 8.1.31 - 8.1.33, 8.2.25 - 8.2.29, 8.3.5 - 8.3.26, 8.4.1 - 8.4.13
- [
{
"customer": "Dr. Kane Hill",
"message_id": 1,
"customer_id": 1,
"messages": [
{
"id": 1,
"created_at": "2024-11-19 11:18:57",
"text": "Hello, how are you?"
},
{
"id": 2,
"created_at": "2024-11-19 11:20:57",
"text": "I am good, thanks! How about you?"
}
]
},
{
"customer": "Prof. Samir McClure III",
"message_id": 2,
"customer_id": 2,
"messages": [
{
"id": 3,
"created_at": "2024-11-19 11:21:57",
"text": "Hey, what time is it?"
},
{
"id": 4,
"created_at": "2024-11-19 11:22:57",
"text": "It is 3 PM."
},
{
"id": 7,
"created_at": "2024-11-19 11:26:57",
"text": "Not bed?"
},
{
"id": 8,
"created_at": "2024-11-19 11:27:57",
"text": "Cool?"
}
]
},
{
"customer": "Shad Leffler",
"message_id": 3,
"customer_id": 3,
"messages": [
{
"id": 5,
"created_at": "2024-11-19 11:23:57",
"text": "Did you finish the project?"
},
{
"id": 6,
"created_at": "2024-11-19 11:24:57",
"text": "New mesh"
}
]
}
]
preferences:
59.53 ms | 412 KiB | 5 Q