문제

Im a dota 2 fan and I am experimenting on the Steam Web API where you can retrieve match history and match details. Take a look at my code in PHP.

$json = '{ "result": {
    "players": [
        {
            "account_id": 4294967295, 
            "player_slot": 0,
            "hero_id": 103,           
            "tower_damage": 1259,
            "hero_healing": 263,
            "level": 17,
            "ability_upgrades": [
                {
                    "ability": 5591,
                    "time": 130,
                    "level": 1
                },
                {
                    "ability": 5589,
                    "time": 333,
                    "level": 2
                },
                {
                    "ability": 5591,
                    "time": 454,
                    "level": 3
                }
            ]

        }
    ]}
}';
$obj = json_decode($json, false);

I want to print the values under the players array which are the account_id, player_slot, hero_id and so on. I'm having troubles at json array as objects. I also want to print the data under the ability_upgrades values, the 3 of them.

도움이 되었습니까?

해결책

1) I think you don't need to convert json to object, it's simpler to convert it to an array

$data = json_decode($json, true);

2) And then you can get any portion of data:

As you said:

I want to print the values under the players array which are the account_id, player_slot, hero_id and so on

It's simple:

foreach($data['players'] as $player)
{
   echo "Account id:" . $player['account_id'] . "\n";
   echo "Player's slot:" . $player['player_slot'] . "\n";
   //And other fields...
   echo "Ability upgrades:";
   foreach($player['ability_upgrades'] as $au)
   {
      echo "Ability:" . $au['ability'] . ", time:" . $au['time'] . ", level:";
      echo $au['level'] . "\n";
   }
}

다른 팁

    $data = json_decode($json, true);
    foreach($data['result']['players'] as $player) {
        // Your code
    }

If you want to convert all object to array, use this function.

function objectToArray($d){ if(is_object($d)){ $d=get_object_vars($d); } if(is_array($d)){ return array_map(__FUNCTION__, $d); } else{ return $d; } }

Takes Your Example... if you print

$obj = json_decode($json, false);

, gives you objects on each node. But after doing like this

$obj = objectToArray(json_decode($json, false));

, using this function got all node as array. So you can print all players in for loop, or print account_id like this...

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