1

I am trying to query and parse Yahoo fantasy sports data and show results in a friendly format.

Here is the JSON I get back from Yahoo from a successful request...

{
"fantasy_content": {
"xml:lang": "en-US",
"yahoo:uri": "\/fantasy\/v2\/users;use_login=1\/teams",
"users": {
  "0": {
    "user": [
      {
        "guid": "1234567890"
      },
      {
        "teams": {
          "0": {
            "team": {
              "team_key": "268.l.auto.t.209996",
              "team_id": "209996",
              "name": "Team Test",
              "type": "auto"
            }
          },
          "1": {
            "team": {
              "team_key": "273.l.auto.t.27741",
              "team_id": "27741",
              "name": "Team API",
              "type": "auto"
            }
          },
          "count": 2
        }
      }
    ]
  },
  "count": 1
},
"time": "29.808044433594ms",
"copyright": "Data provided by Yahoo! and STATS, LLC",
"refresh_rate": false
  }
}

I am looking to get the team names from the teams array. I have tried using the following PHP code (among countless variations of it) to drill to the node I need but I am not having any luck.

$obj=json_decode($json);
$data = $obj->fantasy_content->users->user->teams->team; 
foreach($data as $d){
echo 'name: ' . $d->name ; //prints php 
}  

I am hoping that someone might be able to provide a working example using the JSON above as I have clearly failed at this. Any help would be greatly appreciated.

Thanks in advance!

4

1 回答 1

0

尝试这个

$obj=json_decode($json);
$data = $obj->fantasy_content->users->{'0'}->user[1]->teams; 
foreach($data as $d){
    echo 'name: ' . $d->team->name ; //prints php 
}  

编辑您可以使用 cout 循环遍历名称

$obj=json_decode($json);
$data = $obj->fantasy_content->users->{'0'}->user[1]->teams; 
for($i = 0; $i < $data->count; $i++){
    echo 'name: ' . $data->{$i}->team->name ; //prints php 
}  
于 2012-06-18T23:37:37.297 回答