简体   繁体   中英

json result to array and get result

I have simple API call for themoviedb.org and I get results by external id (imdb_id), but I can't parse and get correct value.

I just want get value of ID --> [id] => 18773

So how I can get stored only themoviedb ID from API?

My code:

$url = "https://api.themoviedb.org/3/find/".$imdbId."?api_key=$apikey&language=en-US&external_source=imdb_id";

$content = file_get_contents($url, false);

// Tried 
$json = json_decode($content, true);

echo $json['id']; // return nothing?


// Testing (check below array return)
$result = array_values(json_decode($content, true));
print("<pre>".print_r($result,true)."</pre>");

Array from $result

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [adult] => 
                    [backdrop_path] => /iSaKc4Nu7hTQDAvJigUVmNwTkj6.jpg
                    [genre_ids] => Array
                        (
                            [0] => 27
                            [1] => 9648
                            [2] => 53
                        )

                    [id] => 18773
                    [original_language] => en
                    [original_title] => Doppelganger
                    [overview] => A woman moves from NYC to LA after a murder, in which she is implicated. She is followed by what is apparently her evil alter- ego. She moves into a room for rent by a writer, and he begins having an affair with her, but after some strange things happen, he's not so sure if the affair is with her or her doppelganger.
                    [poster_path] => /kdMJhjqAlwJekpp8jGu6Lk3Tfy6.jpg
                    [release_date] => 1993-03-01
                    [title] => Doppelganger
                    [video] => 
                    [vote_average] => 5
                    [vote_count] => 56
                    [popularity] => 5.931
                )

        )

    [1] => Array
        (
        )

    [2] => Array
        (
        )

    [3] => Array
        (
        )

    [4] => Array
        (
        )

)

According to the documentation: https://developers.themoviedb.org/3/find/find-by-id you can get the id value by something like this $json['movie_results'][0]['id'] .

But as you can see, the object movie_results is an array so you may have there more than one result or even no results.

So here are some tips what you should consider in your code:

  1. What to do if there are more than one results?
  2. What to do if there are no result at all?

If there is only one result you can safely get the ID.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM