如何在保留值的同时获取数组项的出现次数。例如:$items = [{code: "2132", tile:"Mechanical Engineers"}, {code: "2134" title: "Chemical engineers"}, {code: :2132, title: "Mechanical Engineers}]我想实现的是如下内容:$sortedItems = [{code: "2134" title: "Chemical engineers", count:1}, {code: "2132" title: "Chemical engineers", count:2}]我正在使用Larave,并希望通过使用PHP数组甚至Laravel集合来获得它。以哪个效果更好。感谢您的帮助,因为我真的被困在这里,不知道如何继续。
1 回答
![?](http://img1.sycdn.imooc.com/5458655200013d9802200220-100-100.jpg)
慕慕森
TA贡献1856条经验 获得超17个赞
使用集合和:groupBymap
$items = '[{"code": "2132", "title":"Mechanical Engineers"},
{"code": "2134", "title":"Chemical engineers"},
{"code":"2132", "title":"Mechanical Engineers"}]';
$array = json_decode($items, true);
// try this:
$arr = collect($array)->groupBy('code')->map(function($item) {
return array_merge($item->first(), array("count" => $item->count()));
})->all();
array_values($arr);
- 1 回答
- 0 关注
- 59 浏览
添加回答
举报
0/150
提交
取消