Saxo_Broko
Saxo_Broko

Reputation: 398

How do i get imdb_id from in api using foreach loop

I want to get the imdb_id from inside json using foreach i am having an issue with getting it decoded and displayed.

My php code so far:

$themoviedburl = "http://api.themoviedb.org/3/tv/60625/external_ids?api_key=";
$get = file_get_contents($themoviedburl);
$decode1 = json_decode($get, TRUE);
foreach($decode1['external_ids'] as $value){
    $imdb    = $value['imdb_id'];
}

Json:

{"id":60625,"imdb_id":"tt2861424","freebase_mid":"/m/0z6p24j","freebase_id":null,"tvdb_id":275274,"tvrage_id":33381,"facebook_id":"RickandMorty","instagram_id":"rickandmorty","twitter_id":"RickandMorty"}

Upvotes: -1

Views: 434

Answers (1)

nice_dev
nice_dev

Reputation: 17825

After $decode1 = json_decode($get, TRUE);

You can simply do $imdb_ids = array_column($decode1['external_ids'],'imdb_id'); to collect all imdb_id in one array.

More info on array_column : https://www.php.net/manual/en/function.array-column.php

As discussed in the comments, to get only one imdb_id ID, you can do like below:

$json = '{"id":60625,"imdb_id":"tt2861424","freebase_mid":"/m/0z6p24j","freebase_id":null,"tvdb_id":275274,"tvrage_id":33381,"facebook_id":"RickandMorty","instagram_id":"rickandmorty","twitter_id":"RickandMorty"}';

$decoded_data = json_decode($json,true);

$imdb_id = $decoded_data['imdb_id'];

Upvotes: 1

Related Questions