Akhilendra Pratap Yadav Akhilendra Pratap Yadav - 1 month ago 6
JSON Question

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

Answer

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.