You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法获取TMDB电影ID求助:嵌套数组结构导致取值失败

Fixing TMDB Movie ID Retrieval from Nested Array Response

Hey there! I see you're stuck trying to pull movie IDs from the TMDB API's nested array response—let's break this down and get it sorted out for you.

First, let's clarify the structure of the TMDB /movie/popular API response: all the movie data you need lives under the results key in the decoded array. Your current code correctly decodes the JSON to an associative array, but you haven't targeted that nested results set yet, which is why you can't access individual movie IDs.

Here's a modified version of your code that will let you grab each movie's ID:

<?php
// Fetch the API response
$tmdb_json = file_get_contents('https://api.themoviedb.org/3/movie/popular?api_key=05902896074695709d7763505bb88b4d&language=en-US&page=1');
// Decode JSON to an associative array
$tmdb = json_decode($tmdb_json, true);

// Check if the results array exists to avoid PHP errors
if (isset($tmdb['results']) && is_array($tmdb['results'])) {
    // Loop through each movie entry in the results
    foreach ($tmdb['results'] as $movie) {
        // Extract the movie ID from the nested movie data
        $movie_id = $movie['id'];
        // Example: Output the ID (replace with your own logic)
        echo "Movie ID: {$movie_id}<br>";
    }
} else {
    // Handle cases where the API call fails or returns no results
    echo "Couldn't retrieve movie data. Double-check your API key or request URL.";
}
?>

Quick Tips:

  • The TMDB API always wraps list data (like popular movies) in the results array—this is standard for most pagination-based API endpoints.
  • Adding the isset($tmdb['results']) check prevents errors if the API returns an unexpected response (like an invalid key error).
  • Critical Reminder: Never hardcode your TMDB API key in public code! For production, store it in an environment variable or a secure, non-public config file instead.

内容的提问来源于stack exchange,提问作者B.ROMERO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 15:27:55