Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Jonathan Söder
Jonathan Söder
5,771 Points

Need some pointers with accessing multidimensional associative arrays

Hi!

I'm currently trying to write my own script for TMDB. This is the result I'm getting:

array (size=5)
  'movie_results' => 
    array (size=1)
      0 => 
        array (size=14)
          'adult' => boolean false
          'backdrop_path' => string '/yUztTrOARxj1lgcPyrSCeGWigZO.jpg' (length=32)
          'genre_ids' => 
            array (size=3)
              ...
          'id' => int 170
          'original_language' => string 'en' (length=2)
          'original_title' => string '28 Days Later...' (length=16)
          'overview' => string 'Twenty-eight days after a killer virus was accidentally unleashed from a British research facility, a small group of London survivors are caught in a desperate struggle to protect themselves from the infected. Carried by animals and humans, the virus turns those it infects into homicidal maniacs -- and it's absolutely impossible to contain.' (length=342)
          'release_date' => string '2002-11-01' (length=10)
          'poster_path' => string '/xaYdxi1PBEAYvqknvAmMPK5Eff3.jpg' (length=32)
          'popularity' => float 2.675127
          'title' => string '28 Days Later...' (length=16)
          'video' => boolean false
          'vote_average' => float 6.8
          'vote_count' => int 695
  'person_results' => 
    array (size=0)
      empty
  'tv_results' => 
    array (size=0)
      empty
  'tv_episode_results' => 
    array (size=0)
      empty
  'tv_season_results' => 
    array (size=0)
      empty

checking the generated url in a browser gives me this:

{
movie_results: [
{
adult: false,
backdrop_path: "/yUztTrOARxj1lgcPyrSCeGWigZO.jpg",
genre_ids: [
27,
53,
878
],
id: 170,
original_language: "en",
original_title: "28 Days Later...",
overview: "Twenty-eight days after a killer virus was accidentally unleashed from a British research facility, a small group of London survivors are caught in a desperate struggle to protect themselves from the infected. Carried by animals and humans, the virus turns those it infects into homicidal maniacs -- and it's absolutely impossible to contain.",
release_date: "2002-11-01",
poster_path: "/xaYdxi1PBEAYvqknvAmMPK5Eff3.jpg",
popularity: 2.675127,
title: "28 Days Later...",
video: false,
vote_average: 6.8,
vote_count: 695
}
],
person_results: [ ],
tv_results: [ ],
tv_episode_results: [ ],
tv_season_results: [ ]
}

How do I actually access the key value pairs like original_language, original_title etc? When I'm trying to store for example original_title in variables I get an error saying:

"Notice: Undefined index: original_title in C:\wamp...."

here's my code

//Sends request to TMDB
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $tmdb_request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Accept: application/json"
));

$response = curl_exec($ch);
curl_close($ch);

//Decodes json into assoc. array.
$results = json_decode($response, true);
var_dump($results);

$title = $results['original_title'];

echo $title;

My previous little script based on OMDB was much easier to make since it gave me an easier result to work with:

{
Title: "28 Days Later...",
Year: "2002",
Rated: "R",
Released: "27 Jun 2003",
Runtime: "113 min",
Genre: "Horror",
Director: "Danny Boyle",
Writer: "Alex Garland",
Actors: "Alex Palmer, Bindu De Stoppani, Jukka Hiltunen, David Schneider",
Plot: "Animal activists invade a laboratory with the intention of releasing chimpanzees that are undergoing experimentation, infected by a virus -a virus that causes rage. The naive activists ignore the pleas of a scientist to keep the cages locked, with disastrous results. Twenty-eight days later, our protagonist, Jim, wakes up from a coma, alone, in an abandoned hospital. He begins to seek out anyone else to find London is deserted, apparently without a living soul. After finding a church, which had become inhabited by zombie like humans intent on his demise, he runs for his life. Selena and Mark rescue him from the horde and bring him up to date on the mass carnage and horror as all of London tore itself apart. This is a tale of survival and ultimately, heroics, with nice subtext about mankind's savage nature.",
Language: "English, Spanish",
Country: "UK",
Awards: "9 wins & 26 nominations.",
Poster: "http://ia.media-imdb.com/images/M/MV5BNzM2NDYwNjM3OF5BMl5BanBnXkFtZTYwNDYxNzk5._V1_SX300.jpg",
Metascore: "73",
imdbRating: "7.6",
imdbVotes: "276,853",
imdbID: "tt0289043",
Type: "movie",
Response: "True"
}

//all I had to do was to store them in a variable like this:
$title = $results['Title'];

I'm kinda lost. I assume I have to traverse the arrays somehow? I don't really get a clear picture when googling and landing on stack overflow...

I hope someone can point me in the right direction.

Thanks.

1 Answer

Vedran Brnjetić
Vedran Brnjetić
6,004 Points

Hi, multidimensional arrays are just a few steps further.

For every dimension you have to add another set of [] brackets.

In your case, it would look something like this:

<?php
$original_title=$results['movie_results'][0]['original_title'];

You can read it from your array definition in the beginning for every array you need to add another dimension.

You can also make it easier to yourself by using a $movie variable to store movie info in it.

<?php
$movie=$results['movie_results'][0];
$original_title=$movie['original_title'];

Also, I'd put true to adult property for that particular movie :P

Jonathan Söder
Jonathan Söder
5,771 Points

Awesome! Thank you so much!