Json Decode - PHP

≯℡__Kan透↙ 提交于 2019-12-14 03:25:11

问题


I'm trying decode a json from an one API, but when i try the code:

 <?php
   $json = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=270EBE5B0B2501EE0FC750196325406B&steamids=76561198260508210");
   $decode = json_decode($json,1);
   echo $decode['realname'];
  ?>

This appears:

Notice: Undefined index: realname in C:\Program Files (x86)\EasyPHP-Devserver-16.1\eds-www\CSGrow\index.php on line 26

回答1:


When you inspect the API response closely, then is what the returned value:

{
  "response": {
    "players": [
      {
        "steamid": "76561198260508210",
        "communityvisibilitystate": 3,
        "profilestate": 1,
        "personaname": "xGrow ◔ ⌣ ◔",
        "lastlogoff": 1487378601,
        "commentpermission": 1,
        "profileurl": "http://steamcommunity.com/id/xgrow/",
        "avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/9b/9bc4b0e198dfcc919cbcc781beb5886acaa9daee.jpg",
        "avatarmedium": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/9b/9bc4b0e198dfcc919cbcc781beb5886acaa9daee_medium.jpg",
        "avatarfull": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/9b/9bc4b0e198dfcc919cbcc781beb5886acaa9daee_full.jpg",
        "personastate": 1,
        "realname": "Pedro",
        "primaryclanid": "103582791434436747",
        "timecreated": 1447526746,
        "personastateflags": 0,
        "loccountrycode": "PT"
      }
     ]
   }
}

To create a player object, code as follows:

<?php $json = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=270EBE5B0B2501EE0FC750196325406B&steamids=76561198260508210");
 $decode = json_decode($json,1);

 $player = $decode['response']['players'][0];

 echo $player['realname'];
?>



回答2:


It's because realname is not in the main part of the array. You should see it like this:

json -> "response" -> "players"[0] -> "realname"

So you would need to do something like this:

$realname = $decode->response->players[0]->realname;


来源:https://stackoverflow.com/questions/42315744/json-decode-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!