【发布时间】:2014-12-05 02:51:41
【问题描述】:
我正在尝试使用其他人帮助我的这个函数来循环一个非常大的 json 文件。但下面的代码返回:Warning: Invalid argument supplied for foreach()
这段代码在函数之前执行:
$file = new SplFileObject("bdfile/summoner_leagues_entries_export.json");
while (!$file->eof())
{
$json = json_decode($file->fgets(), true);
var_dump($json);
}
_
function getentry($json)
{
foreach($json as $league)
{
if($league['queue'] == 'RANKED_SOLO_5x5')
{
return $league['entries'][0];
}
return null;
}
}
$entry = getentry($json);
if(isset($entry)) echo $entry['playerOrTeamName'] . ',' . "</br>";
这是var_dump($json); 的输出(只是一个小例子,因为它是一个大文件):
{
"_id" : ObjectId("540449a4f59600af7d285075"),
"leagues" : [{
"name" : "Cassiopeia's Hunters",
"tier" : "GOLD",
"queue" : "RANKED_SOLO_5x5",
"entries" : [{
"playerOrTeamId" : "21893177",
"playerOrTeamName" : "JoKoksa",
"division" : "III",
"leaguePoints" : NumberLong(5),
"wins" : NumberLong(99),
"isHotStreak" : false,
"isVeteran" : false,
"isFreshBlood" : false,
"isInactive" : false,
"miniSeries" : false
}],
"id" : NumberLong(21893177)
}, {
"name" : "Kayle's Patriots",
"tier" : "BRONZE",
"queue" : "RANKED_TEAM_3x3",
"entries" : [{
"playerOrTeamId" : "TEAM-ffbaccc0-b8c0-11e2-b67a-782bcb497d6f",
"playerOrTeamName" : "EloStechers",
"division" : "II",
"leaguePoints" : NumberLong(64),
"wins" : NumberLong(9),
"isHotStreak" : false,
"isVeteran" : false,
"isFreshBlood" : false,
"isInactive" : false,
"miniSeries" : false
}],
"id" : NumberLong(21893177)
}, {
"name" : "Cassiopeia's Infiltrators",
"tier" : "BRONZE",
"queue" : "RANKED_TEAM_5x5",
"entries" : [{
"playerOrTeamId" : "TEAM-ffbaccc0-b8c0-11e2-b67a-782bcb497d6f",
"playerOrTeamName" : "EloStechers",
"division" : "II",
"leaguePoints" : NumberLong(60),
"wins" : NumberLong(11),
"isHotStreak" : false,
"isVeteran" : false,
"isFreshBlood" : false,
"isInactive" : true,
"miniSeries" : false
}],
"id" : NumberLong(21893177)
}],
"summonerId" : NumberLong(21893177),
"region" : "euw",
"updatedAt" : NumberLong(1412719896)
}
编辑 3:
$file = new SplFileObject("bdfile/summoner_leagues_entries_export.json");
while (!$file->eof()) {
$json = json_decode($file->fgets(), true);
foreach($json['leagues'] as $entry) {
echo $entry['entries'][0]['playerOrTeamName'] . ',' . $entry['tier'] . ',' . $entry['entries'][0]['division'] . ',' . $entry['entries'][0]['leaguePoints'] . ',' . $entry['entries'][0]['wins'] . "<br/>";
}
}
$file = null;
编辑 4:
我已经解决了,如果你有兴趣,我可以在这里粘贴代码。
【问题讨论】:
-
这很奇怪,你已经把它解码了,在 var 转储之后你得到了另一个 json 字符串?
-
我不知道,我只是想评估一下警告:
Invalid argument supplied for foreach()这让我发疯。 -
fck,我注意到这只是来自使用 bson 的 mongodb 的转储。你可以在
NumberLong()上看到。但这不应该是 foreach 无法正常工作的原因吗?我成功地从同一个文件中解析了 json 而没有 if 语句。但是当我将 if 语句与 foreach 一起使用时,代码停止工作。查看EDIT 3下的主代码以获取同一 JSON 文件上的工作代码。 -
没人能帮我解决这个问题吗?
-
除非你的输入文件的每一行都是一个孤立的 json 编码字符串(例如,整个 json_encode() 调用结果在一行文本中),那么你的 fgets() 循环将继续要读取“损坏”的 json,因为它只读取较大 json 字符串的一小部分。
标签: php json if-statement foreach