Akhilendra
Akhilendra

Reputation: 1167

How to remove extra array from 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"
       }
  ]
}

Upvotes: 0

Views: 625

Answers (2)

Maxime R.
Maxime R.

Reputation: 133

<?php

$foo = json_decode($yourjson);
$data = [];
foreach($foo->data as $array) $data = array_merge($data, $array);
$foo->data = $data;
$yourjson = json_encode($foo);

EDIT Use of array_merge + Oriented object

Upvotes: 0

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

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.

Upvotes: 2

Related Questions