JulianJ
JulianJ

Reputation: 1309

Getting values from a PHP Object

I am trying to figure out how to echo the genre value from an object created with this programme wrapper that requests json data from 'The Movie Database'. I'm so stuck and grappling to understand Object-oriented PHP so any help would be great. I think the fact it is 'nested' (if that's the correct terminology) might be the issue.

<?php 

    include("tmdb/tmdb-api.php");

    $apikey = "myapi_key";
    $tmdb = new TMDB($apikey, 'en', true);
    $idMovie = 206647;

    $movie = $tmdb->getMovie($idMovie);

    // returns a Movie Object
    echo $movie->getTitle().'<br>';
    echo $movie->getVoteAverage().'<br>';
    echo '<img src="'. $tmdb->getImageURL('w185') . $movie->getPoster() .'"/></li><br>';
    echo $movie->genres->id[28]->name;
?>

All of the other values are echoed just fine but I can't seem to get at genres. The json data looks like this ( some of it).

    { 
    "adult":false, 
    "backdrop_path":"\/fa9qPNpmLtk7yC5KZj9kIxlDJvG.jpg",
    "belongs_to_collection":{
        "id":645,
        "name":"James Bond Collection",
        "poster_path":"\/HORpg5CSkmeQlAolx3bKMrKgfi.jpg",
        "backdrop_path":"\/6VcVl48kNKvdXOZfJPdarlUGOsk.jpg" },
        "budget": 0,
        "genres":[
            { "id": 28, "name": "Action" }, 
            { "id": 12, "name": "Adventure" }, 
            { "id": 80, "name": "Crime" } 
        ], 
    "homepage":"http:\/\/www.sonypictures.com\/movies\/spectre\/",
    "id":206647,
    "imdb_id":"tt2379713",
    "original_language":"en",
    "original_title":"SPECTRE",
    "overview":"A cryptic message from Bond\u2019s past sends him on a trail to uncover a sinister organization. While M battles political forces to keep the secret service alive, Bond peels back the layers of deceit to reveal the terrible truth behind SPECTRE."
}

Upvotes: 0

Views: 198

Answers (1)

some-non-descript-user
some-non-descript-user

Reputation: 616

$movie->genres->id[28]->name

This assumes that id is an array and you want the item with index number 28 from it. What you want is the item containing an id with the value 28 without knowing its index number.

There's no easy way to get to it. You'd have to loop over the array $movie->genres and output the right one. Maybe like this:

$n = 28;
// loop over genres-array
foreach($movie->genres as $i=>$g){
    // check if id of item has right value and if so print it
    if($g->id == $n){
        echo $g->name;
        // skip rest of loop if you only want one 
        break;
    }
}

Upvotes: 2

Related Questions