spCl
spCl

Reputation: 3

Get an specific value in a multidimensional array from an API with PHP

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

Upvotes: 0

Views: 75

Answers (1)

Angel Politis
Angel Politis

Reputation: 11313

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']);
}

Upvotes: 3

Related Questions