最近我问了一个关于如何解析这个JSON提要的问题。给出了答案,但也提出了另一个问题。回声正在为提要中的每个玩家发出重复的记录。我不知道为什么会这样,我希望有人能帮我。
这是我的密码:
$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'] . ' ' . $player['att'] . ' ' . $player['cmp'] . ' ' . $player['yds'] . ' ' . $player['tds'] . ' ' . $player['fgm'] . ' ' . $player['fga'] . '<br>';
}这是JSON:
{
"2015091700":{
"home":{
"abbr":"KC",
"to":0,
"stats":{
"passing":{
"00-0023436":{
"name":"A.Smith",
"att":25,
"cmp":16,
"yds":191,
"tds":0,
"ints":2
}
},
"rushing":{
"00-0026213":{
"name":"J.Charles",
"att":21,
"yds":125,
"tds":1
}
}
}
}
}
}这是给我复制的。见下文。
A.Smith
A.Smith 25
A.Smith 25 16
A.Smith 25 16 191
A.Smith 25 16 191 0
A.Smith 25 16 191 0
A.Smith 25 16 191 0
A.Smith 25 16 191 0
J.Charles 25 16 191 0
J.Charles 21 16 191 0
J.Charles 21 16 125 0
J.Charles 21 16 125 1
J.Charles 21 16 125 1
J.Charles 21 16 125 1
J.Charles 21 16 125 1
J.Charles 21 16 125 1 我希望每个球员都能得到独特的结果。
A.Smith应该是A.Smith 25 16 191 0 2,J.Charles应该是J.Charles 21 125 1,而不是上面看到的。
发布于 2015-10-02 09:59:36
代码实际上并不是创建重复的,您只需打印出每一个间歇的结果。实际上,循环是在每次迭代中覆盖现有键的数据。如果您只有一个播放器的数据,但在这种情况下,多个播放器会导致意外的(错误)结果,这将有效。
一个快速和有点肮脏的解决方案将是保存和重置时,一个新的播放器是启动。在这里,我们假设'name‘键总是存在的,并且总是第一个条目。
$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));
$players = array();
$player = false;
foreach ( $iterator as $key => $value ) {
// The key 'name' marks the start of a new player
if ( $key == 'name' ) {
// If we were already processing a player, save it
if ( is_array($player) ) {
$players[] = $player;
}
// Start a new player
$player = array();
}
// If we are processing a player, save the values
if ( is_array($player) ) {
$player[$key] = $value;
}
}
// Don't forget the last player
$players[] = $player;
// Output the resulting players
print_r($players);
// Or, in your desired output format
// Will give a ton of E_NOTICES on dev setups!
foreach( $players as $player ) {
echo $player['name'] . ' ' . $player['att'] . ' ' . $player['cmp'] . ' ' . $player['yds'] . ' ' . $player['tds'] . ' ' . $player['fgm'] . ' ' . $player['fga'] . '<br>';
}直接从解析的数组中获取数据将更加简洁,但这需要为json提供定义良好的已知格式。
https://stackoverflow.com/questions/32725932
复制相似问题