mauro269 mauro269 - 2 months ago 6
JSON Question

Json to PHP - How to take a specific value from an array nested in a bigger array

I'm trying to use the TheMovieDatabase API to take some information to put on my script.
I've correctly decoded the output using

$data['moviecrew'] = json_decode($movie_crew);


Now, the $data['moviecrew'] array is the following:


"crew":[{"credit_id":"52fe43409251416c750094c5","department":"Directing","id":59026,"job":"Director","name":"Peyton
Reed","profile_path":"/h9lEnyQ60EjKRT3ZAOcrqQVlwn3.jpg"},{"credit_id":"52fe43409251416c750094f3","department":"Writing","id":52934,"job":"Screenplay","name":"Nicholas
Stoller","profile_path":"/qwcx9bdVhmyjWb0KOCdRHDXoFZ9.jpg"},{"credit_id":"52fe43409251416c750094f9","department":"Writing","id":62763,"job":"Screenplay","name":"Jarrad
Paul","profile_path":"/qWaXQi5Pz6jEKw9E2xRuX74phiB.jpg"}, ..


What I would like to do is to take the "Director" name to put in my PHP script.
I tried the following code:

<?php if($moviecrew->crew->job == "Director"){echo $moviecrew->crew->name;} ?>


Unfortunately it doesn't work and it gives me the following error:


A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: film/filmsheet.php
Line Number: 36
Backtrace:
File: /Applications/XAMPP/xamppfiles/htdocs/domain.com/application/views/film/filmsheet.php
Line: 36
Function: _error_handler
File: /Applications/XAMPP/xamppfiles/htdocs/domain.com/application/controllers/Film.php
Line: 106
Function: view
File: /Applications/XAMPP/xamppfiles/htdocs/domain.com/index.php
Line: 315
Function: require_once


The line 36 is just:

<?php if($moviecrew->crew->job == "Director"){echo $moviecrew->crew->name;} ?>


How could I solve this issue? Thanks for your kind support.

Answer

There's a couple of things there one of which may be a copy/paste error from your code sample.

At first you have $data['moviecrew'] then you try and use the variable $moviecrew which is not present in your question. (Is it present in the code?)

Assuming you have done $moviecrew = $data['moviecrew'], you will run into the following problem:

"crew" is an array not an object, so you'd need to loop over them all.

foreach ($moviecrew->crew as $crewMember) {
    if ($crewMember->job === 'Director') {
        echo $crewMember->name;
    }
}

But you want to extract just the director's name, so if we assume there is always only ever one director:-

$director = null;

foreach ($moviecrew->crew as $crewMember) {
    if ($crewMember->job === 'Director') {
        $director = $crewMember->name;
        break;
    }
}

if (!is_null($director)) {
    echo $director;
}