looping through nested arrays

I have a heavily nested array which is returned from an API on another website. It looks like this:




Array

(

    [data] => Array

        (

            [0] => Array

                (

                    [pages] => Array

                        (

                            [0] => Array

                                (

                                    [questions] => Array

                                        (

                                        )


                                )


                            [1] => Array

                                (

                                    [questions] => Array

                                        (

                                            [0] => Array

                                                (

                                                    [answers] => Array

                                                        (

                                                            [0] => Array

                                                                (

                                                                    [choice] => 10375872146

What I need is to create an array of the [choice] elements like this:


[choice] => Array (

    [0] => 123455,

    [1] => 234567,

)

I am able to extract the value from each instance using this code:


$value = ArrayHelper::getValue($arr['data'][0], "pages.1.questions.0.answers.1.choice")

but I don’t know the most efficient mechanism to loop through the nested arrays.

Any help appreciated.

Thanks

Just to elaborate a little more:

I am pulling this data in from the API and then saving it into a database table.

The API returns the data nested in the following sequence:

pages >> questions >> answers >> choice

(There can be multiple questions, answers or choices at each level)

Each layer has an associated ID (see below for an actual extract)


                    [pages] => Array

                        (

                            [0] => Array

                                (

                                    [id] => 247733749

                                    [questions] => Array

                                        (

                                            [0] => Array

                                                (

                                                    [id] => 985997023

                                                    [answers] => Array

                                                        (

                                                            [0] => Array

                                                                (

                                                                    [choice] => 10375872146

                                                                )

Ultimately I want to save the data as follows:


page_id  |  question_id  |  answer_id  |  choice

--------------------------------------------------

123      |  2345         |  34567      |  67890

Having seen a lot of the other Yii2 functionality, I am guessing there is probably a built-in solution to my problem.

Thanks




$array = [

    'foo' => [

        'a' => 'one',

        'b' => 'two',

        'c' => 'three'

    ],

    'bar' => [

        'one' => 'a',

        'two' => 'b',

        'three' => 'c'

    ],

];


foreach ( $array as $key => $val )

{

    echo $key;

    

    if ( is_array($val) && count($val) )

    {

        foreach ( $val as $k => $v ) {

            echo $k . ': ' . $v;

        }

    }

}


Result:


foo

    a: one

    b: two

    c: three


bar

    one: a

    two: b

    three: c



The above displays how to loop through an array that has multiple levels (like yours). The’$key’ of the first level are ‘foo’ and ‘bar’. If their ‘$val’ is an array, we loop through it. The same for the second, only I swapped the keys and vals to illustrate different values.

It didn’t look like you knew how to do a foreach loop on an array? I don’t know why you are specifying the actual index numbers to access the values of the array. If later down the line you modify things stored in the array, it will cause many issues as the index numbers could change.

bad:




$phone = $customer[0][2];



good:




$phone = $customer['profile']['phone']



Just wanted to give a crash course on arrays…


You need to loop through each set of results, and process them. Since I don’t know what your array is, it’s hard to read and doesn’t make sense. So I will use an example of an array of users, that we will loop through, grab what we need, and do something with it.




private function createUser($user)

{

    $model = new User;

    

    $model->username = $user['username'];

    $model->name = $user['name'];

    $model->email = $user['email'];


    if ( ! $model->save() ) {

        // handle the error some way

        return false;

    }

    

    return true;

}


$users = [

    [

        'username' => 'johnsmith22',

        'name' => 'John',

        'email' => 'johnsmith22@example.com',

        'age' = 22,

    ],

    [

        'username' => 'jamesbond',

        'name' => 'Bond',

        'email' => 'jamesbond007@example.com',

        'age' = 51,

    ],

];


foreach ($users as $user)

{

    $this->createUser($user);

}



Notice I didn’t pass ‘age’ to the new User model. I was just showing that we grabbed what we needed, and we didn’t need age. This requires the User model to be created (it is with Yii). However, say these were surveys, you would have a Survey model.

You don’t have to use a model, you could use the query builder: http://www.yiiframework.com/doc-2.0/yii-db-querybuilder.html#insert()-detail

Hope that guides you in the right direction.

Hello Wade,

Here is the actual data coming in from the API:


Array

(

    [per_page] => 100

    [total] => 69

    [data] => Array

        (

            [0] => Array

                (

                    [total_time] => 374

                    [href] => https://api.surveymonkey.net/v3/surveys/######

                    [custom_variables] => Array

                        (

                            [ref] => 38i7zw

                        )


                    [ip_address] => 198.x.x.x

                    [id] => 4917

                    [logic_path] => Array

                        (

                        )


                    [date_modified] => 2016-08-18T10:04:26+00:00

                    [response_status] => completed

                    [custom_value] => 

                    [pages] => Array

                        (

                            [0] => Array

                                (

                                    [id] => 249

                                    [questions] => Array

                                        (

                                        )


                                )


                            [1] => Array

                                (

                                    [id] => 247

                                    [questions] => Array

                                        (

                                            [0] => Array

                                                (

                                                    [id] => 985

                                                    [answers] => Array

                                                        (

                                                            [0] => Array

                                                                (

                                                                    [choice_id] => 103

                                                                )


                                                            [1] => Array

                                                                (

                                                                    [choice_id] => 107

                                                                )


                                                        )


                                                )


                                            [1] => Array

                                                (

                                                    [id] => 985

                                                    [answers] => Array

                                                        (

                                                            [0] => Array

                                                                (

                                                                    [choice_id] => 1037

                                                                )


                                                        )


                                                )


                                        )


                                )


                            [2] => Array

                                (

                                    [id] => 249

                                    [questions] => Array

                                        (

                                        )


                                )

The [choice_id] is the thing I am really interested in but I need to add some of the other details in my table so that I can use them as foreign keys. Here is roughly what the table needs to store:




ref     |  survey_id  |  question_id  |  answer_id

38i7zw  |  4917       |  985          |  103



  • "survey_id" is the key "id" located after "data"

  • "question_id" is the key "id" located after "questions"

  • "answer_id" is the "choice_id"

My plan was to convert the array to the format below after which I could insert it into the table:


array (

  [0] => [

       'ref' => 'abc',

       'survey_id' = '123',

       'question_id' => '234',

       'answer_id' => '345'

    ],

  [1] => [

       ...



I have tried a whole variety of things but just cannot get it right. I have no idea how to solve this problem.

Any help would be appreciated.

Thanks