Json 在对象数组中对相似项进行分组
您好,我有以下JSON:Json 在对象数组中对相似项进行分组,json,laravel,laravel-5,eloquent,Json,Laravel,Laravel 5,Eloquent,您好,我有以下JSON: [ { "name": "Donation", "collection": { "name": "Donation Company 1", "collection": { "id": 1, "category": "Donation", "name": "Some Donation", "price": 10,
[
{
"name": "Donation",
"collection": {
"name": "Donation Company 1",
"collection": {
"id": 1,
"category": "Donation",
"name": "Some Donation",
"price": 10,
"description": "Hahahaha",
"company": "Donation Company 1"
}
}
},
{
"name": "Donation",
"collection": {
"name": "Donation Company 1",
"collection": {
"id": 2,
"category": "Donation",
"name": "Another Donation",
"price": 50,
"description": "LoL",
"company": "Donation Company 1"
}
}
},
{
"name": "Insurance Company 1",
"collection": {
"name": "Hehe",
"collection": {
"id": 3,
"category": "Insurance",
"name": "Lorem Ipsum Solor",
"price": 25,
"description": "Lmao",
"company": "Insurance Company 1"
}
}
},
{
"name": "Insurance Company 2",
"collection": {
"name": "Donation Company 1",
"collection": {
"id": 5,
"category": "Insurance",
"name": "Sample Extra",
"price": 500,
"description": "Lorem ipsum dolor",
"company": "Insurance Company 2"
}
}
}
]
我在尝试将相似的项目组合在一起时遇到问题,因为同一类别中的所有项目都出现在同一类别数组中。
在每个类别中,具有相同公司的所有项目最终都位于相同的公司数组中
这是我试图完成的一个示例,我使用了一个在线编辑器来构建JSON:
我使用了laravelcollect()helper函数来构造我的对象数组,我在foreach循环中尝试了几种组合,已经尝试了几个小时,但仍然无法得到预期的JSON返回。假设您
JSON\u decode()
该JSON字符串并将其存储在$JSON
变量中,您可以执行以下操作:
$collection=collect($json);
$collection=$collection->groupBy('collection.collection.category');
转储
$collection
变量以查看结果。感谢您的输入,但我认为您不理解这个问题,我的问题中显示的JSON对象是当前返回给客户端的对象。如果你按照我帖子中的链接,你会看到我希望如何返回数据。我已经建立了收集,但无法让它以这种方式返回。嗨。也许您需要发布生成JSON字符串的代码,因为我不认为它来自Laravel集合。好了,LaravelCollection
在JSON中应该总是以数组的形式出现。哦,很抱歉,当我看到你的帖子时,我想我已经睡着了,我现在明白了,是的,它确实是一个集合。在您的帮助下,我能够按类别进行分组,以获得以下结果:但是存在第二个分组的问题,我尝试在第一个分组后循环收集,以进一步按公司对项目进行分组,但没有成功。