2017-02-16 104 views
1

可以帮助将json结果修改为另一种结果格式。PHP Laravel将json结果重建为另一种json格式

我有此JSON

{ 
    "_links": {...}, 
    "total": 10, 
    "data": [ 
    { 
     "_links": { ... }, 
     "id": 1, 
     "name": "John Doe", 
     "email": "[email protected]", 
     "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": "[email protected]", 
     "images": [ 
     { 
      "12" : { 
      "name":"Trees", 
      "url":"http://path/of/image.jpg" 
      }, 
      "13" : { 
      "name":"People", 
      "url":"http://path/of/image.jpg" 
      } 
     } 
     ] 
    } 
    ] 
} 

第二JSON我想要的图像标识是图像内的键名目的。我想收集laravel而不是循环。例如:

collect($results)->each(function($value, $key){ 
    //code here... 
}); 

请帮忙。谢谢

+0

看看https://laravel.com/docs/5.4/collections#method-mapwithkeys。你也许可以用它在'data.images' – apokryfos

+2

为什么,第一结构有意义和第二一个不 – RiggsFolly

+0

@RiggsFolly是的,我知道,但我的客户希望这个结果是成功的,它很难解释这是好的,而不是那个。 :) – Cris

回答

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); 
}