SteamAPI 未定义索引

SteamAPI Undefined index

我是 PHP 的初学者,我正在使用 steamapi。我明白了一点,想继续在我的网站上导入我当前的游戏。不是我有问题,当我使用 steamapi 并且我不在游戏中时,steam 没有提供任何东西。当我在游戏中时,代码工作正常(这就是我的想法)。

再多解释一下: 当我在游戏中时:echo $json["response"]["players"][0]["gameextrainfo"]; --> 这给了我现在所在游戏的名称。

当我不在游戏中并且我使用:echo $json["response"]["players"][0]["gameextrainfo"]; --> 我收到此通知:

Undefined index: gameextrainfo in C:\xampp\htdocs\steam\steamapi.php on line 10

所以我认为我遇到的问题是,当我不在玩游戏时 returns 什么都没有?

有人可以帮我解决这个问题吗?

就像我说的,我只是 PHP 的初学者,所以如果这是一个愚蠢的问题,我很抱歉。

Steam api 文档位于:https://developer.valvesoftware.com/wiki/Steam_Web_API

在获取玩家摘要下快速搜索 returns:

gameextrainfo If the user is currently in-game, this will be the name of the game they are playing. This may be the name of a non-Steam game shortcut.

API 文档在您刚开始时可能很难解析,但通常它是获取信息的最佳场所。希望对您有所帮助。

--编辑-- 如果您不在游戏中,则不会返回信息,为此您应该在尝试打印数据之前添加数据检查。

// Set variable for individual player
$playerInfo = $json['response']['players'][0];

// Test if extra info exists in player info array
if (array_key_exists('gameextrainfo', $playerInfo) 
  && !empty($playerInfo['gameextrainfo'])
) {
  // echo info string
  echo $playerInfo['gameextrainfo];
}

未定义索引表示 $json['response']['players'][0] 处的数组不包含键 gameextrainfo

这是有道理的,你不是在玩游戏,所以没有提供额外的信息。

您可以使用

检查某个密钥是否存在

array_key_exists("gameextrainfo", $json["response"]["players"][0])

PHP docs

isset($json["response"]["players"][0]["gameextrainfo"])

PHP docs

在这两种情况下,都假设确实有第一个玩家。您应该检查 steam-api 以查看响应中始终传递/始终存在哪些字段。