可以帮助将json结果修改为另一种结果格式。
我有这个json
{
"_links": {...},
"total": 10,
"data": [
{
"_links": { ... },
"id": 1,
"name": "John Doe",
"email": "john@doe.com",
"images": [
{
"imageid": 12,
"name": "Trees",
"url":"http://path/of/image.jpg"
},
{
"imageid": 13,
"name": "People",
"url":"http://path/of/image.jpg"
},
]
}
]
}
然后我的目标是实现这样的结果:
{
"_links": { ... },
"total": 10,
"data": [
{
"_links": { ... }
"id": 1,
"name": "John Doe",
"email": "john@doe.com",
"images": [
{
"12" : {
"name":"Trees",
"url":"http://path/of/image.jpg"
},
"13" : {
"name":"People",
"url":"http://path/of/image.jpg"
}
}
]
}
]
}
所以基本上在第二个json上我想让imageid成为images对象里面的一个键名。我想收集laravel而不是循环。类似的东西:
collect($results)->each(function($value, $key){
//code here...
});
请帮忙。感谢
答案 0 :(得分:0)
我现在已经让它工作了,但由于循环,我对我的代码不满意。如果你们有想法改进,请发表你的答案。感谢。
感谢apokryfos在mapWithKeys()中的想法。
$newArray = array();
foreach($result['data'] as $k => $v){
$images = $v['images'];
unset($v['images']);
$keyed = collect($images)->mapWithKeys(function($item){
$imageId = $item['imageid'];
$data = [" $imageId" => [
'name' => $item['name'],
'url' => $item['url']
]];
return $data;
});
$v = array_add($v, 'images', $keyed->toArray());
array_push($newArray, $v);
}