【问题标题】:Using PHP to find specific entry in JSON URL response使用 PHP 在 JSON URL 响应中查找特定条目
【发布时间】:2017-10-11 10:14:21
【问题描述】:

我正在尝试确定用户是否属于 Steam 组。为此,我使用 Steam 的 Web API,并使用 URL:

https://api.steampowered.com/ISteamUser/GetUserGroupList/v1/?key=APIKEYHERE&steamid=STEAMID64HERE

获取用户所属的所有组的 JSON 响应。 现在我想知道他们是否属于我使用 PHP 的 ID 为 1111111 的特定组。

如何做到这一点?目前我的代码是这样解码的:

$groupid = "1111111";
$url = "https://api.steampowered.com/ISteamUser/GetUserGroupList/v1/?key=APIKEYHERE&steamid=STEAMID64HERE";
$result = file_get_contents($url);
// Will dump a beauty json :)
$pretty = json_decode($result, true);

这使得 $pretty 变量包含整个 JSON 响应。 我将如何使用 PHP 在如下所示的响应中查找组 ID?

    {
    "response": {
        "success": true,
        "groups": [
            {
                "gid": "4458711"
            },
            {
                "gid": "9538146"
            },
            {
                "gid": "11683421"
            },
            {
                "gid": "24781197"
            },
            {
                "gid": "25160263"
            },
            {
                "gid": "26301716"
            },
            {
                "gid": "29202157"
            },
            {
                "gid": "1111111"
            }
        ]

    }
}

想不通。 有什么帮助吗? :)

【问题讨论】:

  • 请检查我的答案,让我有任何其他帮助
  • 没用,看评论
  • 检查中..请稍候
  • 我已经编辑了我的答案,请再检查一次。并让我知道任何其他帮助..
  • 已回复您的解决方案,但不起作用 - 引发错误。

标签: php mysql json steam


【解决方案1】:

使用以下代码检查响应中是否存在用户

$groupid = "1111111";
$is_exists = false;
$url = "https://api.steampowered.com/ISteamUser/GetUserGroupList/v1/?key=APIKEYHERE&steamid=STEAMID64HERE";
$result = file_get_contents($url);

// Will dump a beauty json :)
$pretty = json_decode($result, true);
foreach ($pretty['response']['groups'] as $key => $value) {
    if($value['gid'] == $groupid) {
        $is_exists = true;
        break;
    }
}

// check is_exists

检查上述变量$is_exists 的真假

【讨论】:

    【解决方案2】:
            $groupid = "1111111";
        $url = "https://api.steampowered.com/ISteamUser/GetUserGroupList  /v1/?key=APIKEYHERE&steamid=STEAMID64HERE";
        $result = file_get_contents($url);
        // Will dump a beauty json :)
        $pretty = json_decode($result);
        $s = $pretty->response->groups;
        foreach($s as $value)
        {
            if((int) $groupid  ==  $value->gid)
            {
                echo  "Found";
            }else
            {
                echo  "Not found";  
            }   
    
        }
    

    【讨论】:

    • 它一直返回 Not found,虽然 groupid 实际上在响应中。
    • @peter :我已经编辑了我的答案,请再检查一次。并让我知道任何其他帮助
    • 注意:尝试在第 8 行的 /var/www/html/test.php 中获取非对象的属性 注意:尝试在 /var/www/html/ 中获取非对象的属性第 8 行的 test.php 警告:在第 9 行的 /var/www/html/test.php 中为 foreach() 提供的参数无效
    猜你喜欢
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    相关资源
    最近更新 更多