你好,我有以下JSON:
[
{
"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:预期-json-输出-当-保存
我使用laravel collect()助手函数来构造我的对象数组,我尝试了几个在foreach循环中的组合,并且已经使用了几个小时,但是仍然无法获得预期的JSON返回。
发布于 2015-10-14 17:26:17
假设您json_decode()
该JSON字符串并将其存储在一个$json
变量中,您可以执行以下操作:
$collection = collect($json);
$collection = $collection->groupBy('collection.collection.category');
转储$collection
变量以查看结果。
https://stackoverflow.com/questions/33138016
复制