skip to Main Content

Below is an example of the array I have compiled so far. I am generating the array from a facebook graph api call and want to remove the Array wrapping each object so I just have one list under the data Array. Preferably I need a dynamic solution as their could be more than one [0] => Array, [1] => Array and so on…. in each API request.

stdClass Object
(
    [data] => Array
        (
            [0] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 21744379694_10154626935079695
                            [created_time] => 2016-10-16T06:29:28+0000
                            [from] => stdClass Object
                                (
                                    [name] => Tony Hawk
                                    [id] => 21744379694
                                )
                        )
                )

            [1] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 50043151918_10154176205946919
                            [created_time] => 2016-10-15T20:04:22+0000
                            [from] => stdClass Object
                                (
                                    [name] => GoPro
                                    [id] => 50043151918
                                )

                        )
                )
        )
)

I would like the array to look like this ultimately. What is the best approach here?

stdClass Object
(
    [data] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 21744379694_10154626935079695
                    [created_time] => 2016-10-16T06:29:28+0000
                    [from] => stdClass Object
                        (
                            [name] => Tony Hawk
                            [id] => 21744379694
                        )
                )
            [1] => stdClass Object
                (
                    [id] => 50043151918_10154176205946919
                    [created_time] => 2016-10-15T20:04:22+0000
                    [from] => stdClass Object
                        (
                            [name] => GoPro
                            [id] => 50043151918
                        )

                )
        )
)

2

Answers


  1. Assuming your data is stored in a variable $data, you can do this:

    foreach($data->data as &$el) {
        $el = $el[0];
    }
    

    Now the wrapping arrays have been removed.

    See it run on eval.in

    Login or Signup to reply.
  2. You can use this:

    if ($data && $data->data){ $new = array_values($data->data); }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search