JSON偶尔未定义-我该如何检查

JSON occasionally undefined - how do I check?

本文关键字:何检查 检查 偶尔 未定义 JSON      更新时间:2023-09-26

所以我试图访问的JSON对象有时不存在。

注意:未定义的索引:C:''examplep''htdocs''example''game.php 中的电影

我正在Steam API中使用game.php上的此代码:

$GLOBALS['gameTrailer'] = $game_json[$trimmed]['data']['movies'][0]['webm']['max'];
echo json_encode(array(
    'gameTrailer' => $GLOBALS['gameTrailer'],
    //+ other variables
));

我正在使用AJAX在index.php:上这样戳game.php

function returnGame () {
            $.ajax({
              url: "game.php",
              type: "post",
              dataType: 'json',
              success: function(data){
                  console.log(data);
                  $('#video').removeAttr('src');
                  ///// Game name /////
                  $('#gameName').html(data.gameName);
                  /////////////////////                   
                  ////// Append and load video /////
                  var videoSrc = data.gameTrailer;
                  var video_block = $('#video');
                  if (videoSrc !== null && videoSrc !== undefined) {
                        video_block.load();
                        document.querySelector('video').src = videoSrc;
                  } else {
                      $("#gameTrailer").find("#gameScreenshot").attr("src", data.gameScreenshot);
                  }
                  //////////////////////////////////
              },  
            }); 
        }

当movies为null时,AJAX函数将不执行任何操作。视频不会变为空白,电影标题也不会更新为新内容。当电影没有定义时,它就完美地工作。

虽然在game.php或index.php上,我似乎无法将$GLOBALS['gameTrailer']捕捉为未定义的,并重新输入或替换为屏幕截图而不是电影。我尝试过if(empty()){}和if($GLOBALS['gameTrailer'] == NULL) {}之类的东西,但即使game.php上的错误代码告诉我它未定义,它看起来也不是。

任何想法都将不胜感激。谢谢

编辑:完整游戏.php代码:

<?php
if(isset($_POST)) {
    fetchGame();
}
function fetchGame() {
    ////////// ID-picker //////////
    $f_contents = file("steam.txt");
    $url = $f_contents[mt_rand(0, count($f_contents) - 1)];             
    $answer = explode('/',$url);
    $gameID = $answer[4];
    $trimmed = trim($gameID);
    ////////// Fetch game //////////
    $json = file_get_contents('http://store.steampowered.com/api/appdetails?appids='.$trimmed);
    $game_json = json_decode($json, true);
    ////////// Store variables //////////
    $GLOBALS['gameName'] = $game_json[$trimmed]['data']['name'];
    $GLOBALS['gameTrailer'] = $game_json[$trimmed]['data']['movies'][0]['webm']['max'];
    $GLOBALS['gameScreenshot'] = $game_json[$trimmed]['data']['screenshots'][0]['path_full'];
    $GLOBALS['gameImage'] = $game_json[$trimmed]['data']['header_image'];
    $GLOBALS['gameId'] = $trimmed;
    $GLOBALS['free'] = $game_json[$trimmed]['data']['is_free'];
    $GLOBALS['price'] = $game_json[$trimmed]['data']['price_overview']['final'];
    if(!isset($GLOBALS['price']) && ($GLOBALS['gameTrailer'])) {
        fetchGame();
    }
    if ($GLOBALS['free'] === TRUE) {
        $GLOBALS['final_price'] = "Free";
    } elseif($GLOBALS['free'] === FALSE || $GLOBALS['final_price'] != NULL) {
        $GLOBALS['final_price'] = $GLOBALS['price'];
    } else {
        $GLOBALS['final_price'] = "-";
    }
}
////////// Return to AJAX (index.php) //////////
echo 
    json_encode(array(
        'gameName' => $GLOBALS['gameName'],
        'gameTrailer' => $GLOBALS['gameTrailer'],
        'gameImage' => $GLOBALS['gameImage'],
        'gameId' => $GLOBALS['gameId'],
        'finalPrice' => $GLOBALS['final_price'],
        'gameScreenshot' => $GLOBALS['gameScreenshot']
    ))
;
?>

它在第23行中断($GLOBALS['gameTrailer'] = $game_json[$trimmed]['data']['movies'][0]['webm']['max'];作为未定义索引)

好的,这里有一个由对问题的评论提供的代码更新示例。

注:

1) 除非你知道自己在做什么以及为什么要使用$GLOBALS,否则不要使用它。在这种情况下,它似乎不是必需的。更新为$game,因为它保存了游戏详细信息。

2) 在尝试访问之前,您需要检查是否存在。因此,您以前拥有的isset是无用的,因为您已经访问了不存在的数组项。删除了那张支票。

3) 递归是好的,但同样,你需要知道你在做什么,以及为什么要使用它。我怀疑这是无意的,但作为2的一部分被删除了。

4) 你说有一个视频(根据它的外观和价格)是这个功能的要求,所以你应该提前检查一下。请注意,获取ID后的第一件事是查看是否有视频。为什么工作只是为了发现我们不能使用它?

5) 如果没有视频,你想尝试另一个游戏,所以我们将检查和分配打包成一个循环,如果没有视频则为continue。请注意,您可能希望将尝试次数限制为n次,否则您可能会等待脚本很长时间才能找到有视频的游戏,但这由您自己决定。

<?php
if(isset($_POST)) {
    fetchGame();
}
function fetchGame() {
    $gameFound = false;
    while(!$gameFound) {
        ////////// ID-picker //////////
        $f_contents = file("steam.txt");
        $url = $f_contents[mt_rand(0, count($f_contents) - 1)];             
        $answer = explode('/',$url);
        $gameID = $answer[4];
        $trimmed = trim($gameID);
        ////////// Fetch game //////////
        $json =     file_get_contents('http://store.steampowered.com/api/appdetails?appids='.$trimmed);
        $game_json = json_decode($json, true);
        if(!isset($game_json[$trimmed]['data']['movies'][0]['webm']['max']) || !isset($game_json[$trimmed]['data']['price_overview']['final'])) {
            continue;
        }
        $gameFound = true;
        ////////// Store variables //////////
        $game['gameName'] = $game_json[$trimmed]['data']['name'];
        $game['gameTrailer'] = $game_json[$trimmed]['data']['movies'][0]['webm']['max'];
        $game['gameScreenshot'] = $game_json[$trimmed]['data']['screenshots'][0]['path_full'];
        $game['gameImage'] = $game_json[$trimmed]['data']['header_image'];
        $game['gameId'] = $trimmed;
        $game['free'] = $game_json[$trimmed]['data']['is_free'];
        $game['price'] = $game_json[$trimmed]['data']['price_overview']['final'];
        if ($game['free'] === TRUE) {
            $game['final_price'] = "Free";
        } elseif($game['free'] === FALSE || $game['final_price'] != NULL) {
            $game['final_price'] = $game['price'];
        } else {
            $game['final_price'] = "-";
        }
    }
}
////////// Return to AJAX (index.php) //////////
echo 
    json_encode(array(
        'gameName' => $game['gameName'],
        'gameTrailer' => $game['gameTrailer'],
        'gameImage' => $game['gameImage'],
        'gameId' => $game['gameId'],
        'finalPrice' => $game['final_price'],
        'gameScreenshot' => $game['gameScreenshot']
    ));
?>

请注意,此代码未经测试,但我希望能让您了解如何继续。