laravel - Laravel 中的 Json 格式
问题描述
我有这个 JSON。
{
"animals": [{
"name": "Cumi-Cumi",
"data": 1000
}, {
"name": "Udang",
"data": 300
}, {
"name": "Baranang",
"data": 12000
}, {
"name": "Cumi-Cumi",
"data": 1500
}, {
"name": "Udang",
"data": 500
}, {
"name": "Baranang",
"data": 17000
}, {
"name": "Cumi-Cumi",
"data": 2500
}]
}
如何data
按名称对密钥进行分组,如下所示:
{
"animals": [{
"name": "Cumi-Cumi",
"data": [
1000, 1500, 2500
]
},
{
"name": "udang",
"data": [
300, 500
]
},
{
"name": "Baranang",
"data": [
12000, 17000
]
}
]
}
解决方案
可能是因为我累了,但我不知道如何使这个更简洁......
无论如何这对你来说是一个开始。
$json = '{
"animals": [{
"name": "Cumi-Cumi",
"data": 1000
}, {
"name": "Udang",
"data": 300
}, {
"name": "Baranang",
"data": 12000
}, {
"name": "Cumi-Cumi",
"data": 1500
}, {
"name": "Udang",
"data": 500
}, {
"name": "Baranang",
"data": 17000
}, {
"name": "Cumi-Cumi",
"data": 2500
}]
}';
// Start by decoding the JSON (I assume it comes as a string, if not, then ignore this).
$collection = collect(json_decode($json, true))
// Now iterate over the keys (you only have one key (animals), but I wanted to be safe).
->map(function ($item) {
// Convert the sub arrays into a Collection, then group the data against each animal name.
// Then map (iterate) over each of the animals, one at a time.
return collect($item)->groupBy('name')->map(function ($animal) {
// Reduce each animal into a single entry.
return $animal->reduce(function ($carry, $data) {
// Use the name of the animal, then push the data onto the end. Feel free to sort at this point too!
$carry['name'] = $data['name'];
$carry['data'][] = $data['data'];
return $carry;
});
// Finally, I reset the groupBy keys to ensure it matches your desired output.
})->values();
});
推荐阅读
- java - java - 如何使控制器端点在java spring中获取两个不同的对象?
- jquery - AJAX 没有得到 API 的响应
- android - 对话框中的Webview连续上下滚动
- microsoft-edge-extension - 替代缺少身份的API?
- javascript - 功能未定义 - 外部 JS
- python - SSHException:通道关闭
- xml - 根据值移除 SVG/XML 子元素
- java - 如何在网络应用程序中将谷歌日历与 acc 同步
- google-bigquery - 如何在 where 条件下选择两个事件名称值
- android - 将 iPhone 应用程序徽标转换为 Android