Search code examples
phpjsonlaravel-5.3

PHP Laravel reconstructing the json result to another json format


can soeone help to modify the json result to another result format.

I have this 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"
        },
      ]
    }
  ]
}

Then my goal is to achieve this kind of result:

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

SO basically on the second json I want the imageid to be a keyname inside the images object. I would like to collection in laravel instead of looping. something like:

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

Please help. Thanks


Solution

  • I got it to worked for now, but I'm not satisfied with my code because of the loop. if you guys have an idea to improve, please post your answer. Thanks.

    Thanks to apokryfos for the idea in 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);
    }