mauro269 mauro269 - 3 months ago 10
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:

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
File: /Applications/XAMPP/xamppfiles/htdocs/
Line: 36
Function: _error_handler
File: /Applications/XAMPP/xamppfiles/htdocs/
Line: 106
Function: view
File: /Applications/XAMPP/xamppfiles/htdocs/
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.


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;

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