我在这里有一个情况。我有如下收藏
Collection
Array:2
(
0 =>
+"id": 26
+"st_crime": "AMEAÇA CONTRA MENOR"
}
1 =>
+"id": 26
+"st_crime": "ARREBATAMENTO DE PRESO"
}
)
我想得到如下输出:
Collection
Array:1
(
0 =>
+"id": 26
+"st_crime": "AMEAÇA CONTRA MENOR, ARREBATAMENTO DE PRESO"
}
)
欢迎任何帮助
答案 0 :(得分:0)
$col = collect([
(object) ['id' => 26, 'st_crime' => 'AMEAÇA CONTRA MENOR'],
(object) ['id' => 26, 'st_crime' => 'ARREBATAMENTO DE PRESO']
]);
$col->groupBy('id')->map(function ($group) {
$struct = clone $group->first();
$struct->st_crime = $group->pluck('st_crime')->implode(', ');
return $struct;
});
// result
=> Illuminate\Support\Collection {#2980
all: [
26 => {#2983
+"id": 26,
+"st_crime": "AMEAÇA CONTRA MENOR, ARREBATAMENTO DE PRESO",
},
],
}
无需研究更通用的方法即可满足特定需求。
奖金:
使用Tappity-tap-tap-tap
:
$col->groupBy('id')->map(function ($group) {
return tap(clone $group->first(), function ($item) use ($group) {
$item->st_crime = $group->pluck('st_crime')->implode(', ');
});
});