Search code examples
phpjsonlaravellaravel-collection

Transform Json Array


I have a json like this being retrieved by my model:

[
    {
      "type": "seat",
      "number": 4
    },
    {
      "type": "seat",
      "number": 8
    },
    {
      "type": "seat",
      "number": 12
    },
    {
      "type": "seat",
      "number": 16
    }
]

However due to some poorly written code in the API I'm working with I need to get the above json looking this instead:

{
  "4" : [ "{\"number\":\"4\",\"type\":\"seat\"}" ],
  "8" : [ "{\"number\":\"8\",\"type\":\"seat\"}" ],
  "12" : [ "{\"number\":\"12\",\"type\":\"seat\"}" ],
  "16" : [ "{\"number\":\"16\",\"type\":\"seat\"}" ]
}

I would like to know how I can transform the first example to look like the second example using collections in laravel.


Solution

  • This seems pretty straight forward:

    $data = json_decode($json, true);
    
    collect($data)
        ->mapWithKeys(function ($item) {
            return [$item['number'] => [json_encode($item)]];
        })
        ->toArray();