我有这样的数组:
[
0: {name: "Judi", age: 15, hobby: "playing a game"},
1: {name: "Judi", age: 15, hobby: "swimming"},
2: {name: "Judi", age: 15, hobby: "playing a basketball"},
3: {name: "Jedi", age: 14, hobby: "coding"},
4: {name: "Jedi", age: 14, hobby: "reading"},
5: {name: "Jedi", age: 14, hobby: "listen to the music"},
]
我想让我的数据看起来像这样:
[
0: {name: "Judi", age: 15, hobby: "playing a game, swimming, playing a basketball"},
0: {name: "Jedi", age: 14, hobby: "coding, reading, listen to the music"},
]
如何对我的数据进行这样的分组?
如果“名称”字段是标识符,您可以使用一些 Collection 方法来完成此操作:
collect($data)->groupBy('name')->map(function ($group) {
return ['hobby' => $group->pluck('hobby')->join(', ')] + $group->first();
})->values();
这假设您的数据是数组的数组。
collect
这确实是一个非常简单的迭代和新数组的构建。像这样的东西。
<?php
$array = [
['name' => 'Judi', 'age' => 15, 'hobby' => 'playing a game'],
['name' => 'Judi', 'age' => 15, 'hobby' => 'swimming'],
['name' => 'Judi', 'age' => 15, 'hobby' => 'playing a basketball'],
['name' => 'Jedi', 'age' => 14, 'hobby' => 'coding'],
['name' => 'Jedi', 'age' => 14, 'hobby' => 'reading'],
['name' => 'Jedi', 'age' => 14, 'hobby' => 'listen to the music'],
];
$result = [];
foreach ($array as $item) {
$key = $item['name'] . $item['age'];
if (!array_key_exists($key, $result)) {
$result[$key] = [
'name' => $item['name'],
'age' => $item['age'],
'hobby' => '',
];
}
$result[$key]['hobby'] = $result[$key]['hobby'] ? $result[$key]['hobby'] . ', ' . $item['hobby'] : $item['hobby'];
}
var_dump(array_values($result));