Всем привет! Можете подсказать, как реализовать логику преобразования массива `messages` в новый массив `messages2`? Нужно сгруппировать сообщения по значению `customer_id`, сохранив их порядок отображения. В данном случае первым делом необходимо объединить элементы с `customer_id`, равным 1 и 2, затем 3 и 4 и так далее. Вот пример массивов:
```javascript
"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?"
}
]
"messages2": [
{
"customer": "Dr. Kane Hill",
"messages_id": 1,
"customer_id": 1,
"messages": [
{
"id": 1,
"created_at": "2024-11-19 11:18:57",
"text": "Hello, how are you?",
},
{
"id": 2,
```
Для реализации преобразования массива `messages` в новый массив `messages2`, где сообщения группируются по `customer_id`, можно использовать метод `reduce` в JavaScript. Пример ниже показывает, как можно это сделать:
```javascript
const 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?"
}
];
const messages2 = Object.values(messages.reduce((acc, message) => {
// Формируем ключ по customer_id
const key = message.customer_id;
// Если ключа нет - создаём новый
if (!acc[key]) {
acc[key] = {
customer: message.customer,
messages_id: key,
customer_id: key,
messages: []
};
}
// Добавляем текущее сообщение в массив messages
acc[key].messages.push({
id: message.id,
created_at: message.created_at,
text: message.text
});
return acc;
}, {}));
console.log(messages2);
```
### Пояснение к коду:
1. **Reduce**: Используется для обхода каждого элемента массива `messages`. В качестве аккумулятора выступает объект, который будет хранить сгруппированные сообщения.
2. **Ключ для группировки**: В качестве ключа для группировки используется `customer_id`. Если сообщения с таким `customer_id` еще не добавлены в аккумулятор, создается новый объект с основными данными клиента.
3. **Добавление сообщений**: Каждое сообщение добавляется в массив `messages` внутри соответствующего объекта.
4. **Формат вывода**: В конце мы используем `Object.values()` для преобразования результирующего объекта (`acc`) обратно в массив.
Запустив этот код, вы получите требуемый массив `messages2`, где сообщения сгруппированы по `customer_id` с сохранением их порядка.
Делается одним проходом в цикле <br/> Ключем выставляем поле по которому делать группировку и внутрь уже ложим нужные данные <br/> В конце array_values() чтобы переиндексировать результат и сбросить ключи <br/> <br/> <a href="https://3v4l.org/Z2n4V#v8.3.14" rel="nofollow">https://3v4l.org/Z2n4V#v8.3.14</a> <br/> <br/> <pre><code class="php"><?php
$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 = [];
foreach($messages as $row) {
$key = $row['customer_id'];
$messages2[$key]['customer']
= $messages2[$key]['customer'] ?? $row['customer'];
$messages2[$key]['message_id']
= $messages2[$key]['message_id'] ?? $row['id'];
$messages2[$key]['customer_id']
= $messages2[$key]['customer_id'] ?? $row['customer_id'];
$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);</code></pre>