문제

I'm currently messing around with JSON. I have to variables: $a and $b.

$a retrieves a JSON file from a website:

    $a = file_get_contents("http://backpack.tf/api/IGetUsers/v2/?steamids=76561198037411448&format=json");

$b decodes it

    $b = json_decode($a, true);

I did var_dump on $b to confirm that it is, in fact, an array.

I attempted to echo $b["name"], but nothing was returned.

I have no clue what's wrong; nothing is being returned.

도움이 되었습니까?

해결책

You have a multidimensional set of data, instead of $b["name"] What you want is:

$b["response"]["players"][0]["name"]

This is the json objects structure from that URL

{
    "response": {
        "success": 1,
        "current_time": 1369778504,
        "players": {
            "0": {
                "steamid": "76561198037411448",
                "success": 1,
                "backpack_value": 185.86,
                "backpack_update": 1369543543,
                "name": "Paranoid Android",
                "stats_tf_reputation": 1,
                "notifications": 0
            }
        }
    }
}

If you need iteration, will have to loop through $b["response"]["players"]

다른 팁

Maybe you want something like this? I'm only guessing that there could be more than 1 player.

for($i = 0;$i<count($b["response"]["players"]);$i++)
{
   echo $b["response"]["players"][$i]["name"]
}

Well, this is the JSON that is returned:

{
    "response": {
        "success": 1,
        "current_time": 1369778435,
        "players": {
            "0": {
                "steamid": "76561198037411448",
                "success": 1,
                "backpack_value": 185.86,
                "backpack_update": 1369543543,
                "name": "Paranoid Android",
                "stats_tf_reputation": 1,
                "notifications": 0
            }
        }
    }
}

If $b = json_decode($a), then simply using $b['name'] will not work. That key is not set.

You will have to follow the nesting of object literals. Something like this should work:

echo $b['response']['players']['0']['name'];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top