Wednesday, 29 August 2018

How to delete the extra array of Json data in PHP

I want to remove Extra array from this JSON "data". how to do this in PHP. Is it any function in PHP that solve it.?

 {
   "data": [
     [
       {
          "user_id": "654120",
          "user_name": "Jhon_Thomsona",
          "user_image": null
       }
     ],
     [
       {
          "user_id": "1065040766943114",
          "user_name": "Er Ayush_Gemini",
          "user_image": "KP8LSHQFwk.png"
       }
     ]
  ]
}

I want my final array to look like this:
 {
   "data": [
       {
          "user_id": "654120",
          "user_name": "Jhon_Thomsona",
          "user_image": null
       },
       {
          "user_id": "1065040766943114",
          "user_name": "Er Ayush_Gemini",
          "user_image": "KP8LSHQFwk.png"
       }
  ]
}


You can remove the extra array layer around each user object by mapping reset over the elements of data, then reencoding as JSON.
$data = json_decode($json);
$data->data = array_map('reset', $data->data);
$json = json_encode($data);

Of course, if you are creating this JSON yourself, you should avoid creating this structure to begin with rather than altering it after the fact.

0 comments:

Post a Comment