【问题标题】:PHP JSON Decode with number [duplicate]PHP JSON解码带数字[重复]
【发布时间】:2017-11-14 21:40:10
【问题描述】:

我想在我的网站上显示来自 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) 或变量

【问题讨论】:

    标签: php json decode


    【解决方案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'];
    //....
    

    【讨论】:

    • 完美,非常感谢
    猜你喜欢
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多