注意:未定义的偏移量&试图获得非对象的属性

时间:2016-06-01 20:24:48

标签: php

我正在尝试从json_decode数组中提取数据,我之前已经完成了,但这次我遇到了额外的问题。

这就是json的样子。

{
"achievementpercentages": {
    "achievements": [
        {
            "name": "TF_SCOUT_LONG_DISTANCE_RUNNER",
            "percent": 54.668815612792969
        },
        {
            "name": "TF_HEAVY_DAMAGE_TAKEN",
            "percent": 47.104038238525391
        },
        {
            "name": "TF_GET_CONSECUTIVEKILLS_NODEATHS",
            "percent": 44.668777465820312
        },
        {
            "name": "TF_PYRO_CAMP_POSITION",
            "percent": 36.480117797851563
        },
        {
            "name": "TF_KILL_NEMESIS",
            "percent": 34.392494201660156
        },
        {
            "name": "TF_BURN_PLAYERSINMINIMUMTIME",
            "percent": 33.580135345458984
        },
        {
            "name": "TF_PYRO_BURN_MEDICPAIR",
            "percent": 32.748367309570312
        },

我的代码基本上就是这个

$achName = $decodedAch->achievementpercentages->achievements[$achCounter]->name;
$achPercent = $decodedAch->achievementpercentages->achievements[$achCounter]->percent;

$ achCounter出现在while语句中,旨在分别获得所有成就。我不认为这部分是错误的,只是我试图访问数组中的数据。我不知道它有什么问题。

任何帮助将不胜感激。

在要求声明的情况下完整

        while($achCounter < $responseCount)
    {
        $appid = $decodedSteam->response->games[$achCounter]->appid;
        $achievementURL = 'http://api.steampowered.com/ISteamUserStats/GetGlobalAchievementPercentagesForApp/v0002/?gameid='.$appid.'&format=json';
        $jsonAch = file_get_contents($achievementURL);

        $decodedAch = json_decode($jsonAch);
        //var_dump($decodedAch);
        $achName = $decodedAch->achievementpercentages->achievements[$achCounter]->name;
        $achPercent = $decodedAch->achievementpercentages->achievements[$achCounter]->percent;
        //echo $achievementURL;
        $sql = "INSERT INTO steamid".$steamid."(name, percent) VALUES ('".$achName."','".$achPercent."')";
        $achCounter++;

    }

1 个答案:

答案 0 :(得分:0)

从网址获取数据后,您需要再次进行迭代。您的$ achCounter仅适用于$decodedSteam,不适用于$decodedAch

while($achCounter < $responseCount)
{
    $appid = $decodedSteam->response->games[$achCounter]->appid;
    $achievementURL = 'http://api.steampowered.com/ISteamUserStats/GetGlobalAchievementPercentagesForApp/v0002/?gameid='.$appid.'&format=json';
    $jsonAch = file_get_contents($achievementURL);

    $decodedAch = json_decode($jsonAch);
    //var_dump($decodedAch);
    foreach($decodedAch->achievementpercentages->achievements as $achievement) { //HERE
        $achName = $achievement->name;
        $achPercent = $achievement->percent;
        //echo $achievementURL;
        $sql = "INSERT INTO steamid".$steamid."(name, percent) VALUES ('".$achName."','".$achPercent."')";
    }
    $achCounter++;
}