0

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"
       }
  ]
}
4
  • Can you explain what mean by "extra array"? (I think I know, just not sure...) Commented Oct 28, 2016 at 14:53
  • There is no PHP function that reads your mind and removes whatever you deem unnecessary. You have to write it yourself. Commented Oct 28, 2016 at 14:55
  • I want 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" } ] Commented Oct 28, 2016 at 14:55
  • you don't "remove from json". You never manipulate the json. You manipulate the data structure the json was created FROM. Commented Oct 28, 2016 at 15:00

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0
<?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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.