0

I've been trying for a while to find out why I get an error when trying to traverse this array that the Youtube API generates (tree obtained by print_r):

Array
(
    [nextPageToken] => CAIQAA
    [items] => Array
        (
            [0] => Array
                (
                    [snippet] => Array
                        (
                            [resourceId] => Array
                                (
                                    [videoId] => sGIm0-dQd8M
                                )

                        )

                )

            [1] => Array
                (
                    [snippet] => Array
                        (
                            [resourceId] => Array
                                (
                                    [videoId] => VGd1ml4Hvas
                                )

                        )

                )

        )

)

In the first instance, I tried foreach but it generates an error:

$data_decode = json_decode($data, true); //here I get my array

foreach ($data_decode as $decode){
    foreach ($decode as $code){
        echo $code['snippet']['resourceId']['videoId'];
    }
}

Invalid argument supplied for foreach()

I think the problem is for the "nextPageToken" node, which I need to have. What is the correct way to traverse this array?

1
  • a few levels too shallow. $code is an array that contains nextPageToken and items as keys. So snippet is in array[items][0]['snippet'] Commented Mar 28, 2018 at 4:47

1 Answer 1

1
foreach ($data_decode['items'] as $item){
   echo $element['snippet']['resourceId']['videoId'];
}

Just a tip, it's much easier on me if you use var_export instead of print_r var_export will print an array that is syntactically correct for PHP, print_r prints an array in a human readable format.

Therefor I have to take your example data and replace all the [key] with "key" quote the values and add in commas before I can use it in code to test with.

I can do it, but it's tedious.

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

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.