解析 JSON 个供稿

Parse a JSON feed

我在 NFL 游戏中心 JSON 提要中检索 "name"、"att"、"cmp" 和 "yds" 时遇到问题。使用 PHP.

如何在不对“2015091700”和“00-0023436”进行硬编码的情况下检索这些值?

http://www.nfl.com/liveupdate/game-center/2015091700/2015091700_gtd.json

{  
"2015091700":{  
  "home":{  
     "stats":{  
        "passing":{  
           "00-0023436":{  
              "name":"A.Smith",
              "att":25,
              "cmp":16,
              "yds":191
           }
        }
     }
  }
 }
}

这是我现在拥有的代码。

$url  = file_get_contents("http://www.nfl.com/liveupdate/game-center/2015091700/2015091700_gtd.json");
$json = json_decode($url, true); // 'true' makes data an array
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($json)); 
$player = array();

foreach($iterator as $key=>$value) {
  $player[$key] = $value;
  echo $player['name'];
}

这接近我需要的。然而,页面吐出:

A.Smith 
A.Smith
A.Smith
A.Smith
A.Smith
A.Smith
A.Smith
A.Smith
J.Charles
J.Charles
J.Charles
J.Charles
J.Charles
J.Charles
J.Charles
J.Charles
A.Smith
A.Smith
A.Smith
A.Smith
A.Smith

我不确定为什么会得到重复值。如何使它反映 JSON 提要的内容?理想情况下,我想创建一个可以插入到我的 MySQL 数据库 table.

中的查询字符串

这有帮助吗?

$decoded = json_decode($json,true);
var_dump($decoded['2015091700']);

将 JSON 解码为关联数组,然后用 foreach 对其进行循环。

$data = json_decode($json, true);
foreach($data as $key=>$val){
    // $key = 2015091700
    // $val = an associative array with one row.
    // ['home' => ... ]
}

一种方法是使用 PHP 的 RecursiveIteratorIterator class which allows you to iterate through any of the other iterator classes and the RecursiveArrayIterator class which allows easy iteration through an array. These are part of PHP's SPL Library。你可以这样使用它:

<?php
$data = '{
"2015091700":{  
  "home":{  
     "stats":{  
        "passing":{  
           "00-0023436":{  
              "name":"A.Smith",
              "att":25,
              "cmp":16,
              "yds":191
           }
        }
     }
  }
 }
}';

$json = json_decode($data, true); // 'true' makes data an array

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($json)); 

foreach($iterator as $key=>$value) {
    echo $key .' '. $value . '<br />';
}

?>

结果是:

name A.Smith
att 25
cmp 16
yds 191

EXAMPLE

如果您想将单个位放入变量中,最简单的方法是对代码进行小的更改:

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($json)); 

$player = array();

foreach($iterator as $key=>$value) {
    $player[$key] = $value;

}
echo $player['name'];

这使您可以描述玩家并将按键正确分配给玩家。上面的结果将是:

A.Smith

现在您可以根据需要使用玩家数据的各个部分,因为它们很容易通过密钥识别。