2017-02-16 9 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" 
     }, 
     ] 
    } 
    ] 
} 

はその後、私の目標は、その結果、この種の達成することですがあります:私はIMAGEIDは、画像内のキー名になりたい二JSONにSO基本的に

{ 
    "_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" 
      } 
     } 
     ] 
    } 
    ] 
} 

をオブジェクト。ループの代わりにlaravelでコレクションしたいです。次のようなもの:

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

助けてください。ありがとう

+0

。あなたはおそらくdata.images' – apokryfos

+2

はなぜ、最初の構造は感覚と第二を作る 'でそれを使用することができますhttps://laravel.com/docs/5.4/collections#method-mapwithkeysを見てみましょう1つは – RiggsFolly

+0

@ RiggsFollyええ私は知っているが、私のクライアントは、結果が達成されることを望んでいると、これは良いことではなく、そのことを説明することが欲しい。 :) – Cris

答えて

0

私は今のところ働いているが、私はループのために自分のコードに満足していない。もし皆さんが改善すべきアイデアを持っているなら、あなたの答えを投稿してください。ありがとう。

mapWithKeys()のアイディアのためapokryfosに感謝します。

$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); 
} 
関連する問題