PHP JSON用数字解码

时间:2017-06-13 08:18:24

标签: php json decode

我想在我的网站上显示API https://steamgaug.es/api/v2中的一些信息。

这是我目前的代码:

 $steamStatusJson = @file_get_contents("https://steamgaug.es/api/v2");
 $steamStatus = json_decode($steamStatusJson);
 $csgoStatus = $steamStatus->ISteamGameCoordinator->730->online;
 $csgoplayerssearching = $steamStatus->ISteamGameCoordinator->730->stats->players_searching;
 $csgoplayers =  $steamStatus->ISteamGameCoordinator->730->stats->players_online;

我总是收到此错误消息:

  

FATAL ERROR语法错误,意外' 730' (T_LNUMBER),期待标识符(T_STRING)或变量

1 个答案:

答案 0 :(得分:1)

与您将json解码为对象一样,您不能将数字用作properties names

所以,你需要这一行:

$csgoStatus = $steamStatus->ISteamGameCoordinator->730->online;

应如下:

$csgoStatus = $steamStatus->ISteamGameCoordinator->{"730"}->online;
//                                                 ^^^^^^^

也与这些行相同:

$csgoplayerssearching = $steamStatus->ISteamGameCoordinator->{"730"}->stats->players_searching;
$csgoplayers =  $steamStatus->ISteamGameCoordinator->{"730"}->stats->players_online;

或者,简单地将json解码为数组

$steamStatus = json_decode($steamStatusJson, true);

然后你可以访问它:

$csgoStatus = $steamStatus['ISteamGameCoordinator']['730']['online'];
//....