0

I'm trying get the values of an array but the maximum I can do is

$characters = $array['data']['results'];

Why can't I go deeper in the array like doing $characters['stories'] for example?

See picture as an example. So if I want to show in my page the name of the series, how can I bring this value? I know it's a beginner question. A colleague told me to use array_key_exists but in other answers in stackoverflow people suggest other things, is there an unique way or a more correct way to do that? By the way, I tried to adapt answers and it didn't work.

Arrays with results from API

1 Answer 1

3

As you can see in the image, after results there's a property named 0. In order to be able to get stories, you need to use:

$characters = $array['data']['results'];
$characters[0]['stories'];

If there are more numeric indices like that and you want to traverse each, you'll have to use a for or foreach loop.

Example: (using foreach)

foreach ($characters as $character) {
    # Print the stories array for each character.
    print_r($character['stories']);
}

Example: (using for)

for ($index = 0; $index < count($characters); $index++) {
    # Print the stories array for each character.
    print_r($characters[$index]['stories']);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Shouldn't your first example say print_r($character['stories']); - I mean singular character?
Yes, thanks @uom-pgregorio. I answered this question from my phone and auto-correct did its thing again...
Thank you @angel-politis, it solved my problem, thanks for your help and explanation! :)

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.