使用PHP在JSON URL响应中查找特定条目

时间:2017-10-11 10:14:22

标签: php mysql json steam

我试图找出用户是否属于Steam组。为此,我使用的是Steam的Web API,并使用URL:

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

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

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

$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"
            }
        ]

    }
}

无法弄明白。 有帮助吗? :)

2 个答案:

答案 0 :(得分: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是否为true或false

答案 1 :(得分:1)

        $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";  
        }   

    }