我遇到以下情况:我正在获取有关 JSON 格式游戏的信息。该游戏中有多个玩家,有多个物品。
播放器代码如下所示:
$playerOne = $json->games[$i]->fellowPlayers[0];
$playerTwo = $json->games[$i]->fellowPlayers[1];
$playerThree = $json->games[$i]->fellowPlayers[2];
$playerFour = $json->games[$i]->fellowPlayers[3];
$playerFive = $json->games[$i]->fellowPlayers[4];
$playerSeven = $json->games[$i]->fellowPlayers[6];
$playerEight = $json->games[$i]->fellowPlayers[7];
$playerNine = $json->games[$i]->fellowPlayers[8];
$i是我的 for 循环中的变量。我没有添加其余代码,因为它不需要。
所以这就是我要解决的问题。 并非所有玩家和物品插槽总是被填满。所以我需要一种方法来检查它们是否在 JSON 中。
我试过了:
if(!is_null($json->games[$i]->fellowPlayers[5])){
$playerSix = $json->games[$i]->fellowPlayers[5];
}
但这没有用。提前泰
if (isset($json->games[$i]->fellowPlayers[5]))
{
$playerSix = $json->games[$i]->fellowPlayers[5];
}
检查具有此类索引的数组成员是否存在,然后将其分配给变量。您还可以执行所需的任何其他检查。
if(!empty($json->games[$i]->fellowPlayers[0])){
$playerOne = $json->games[$i]->fellowPlayers[0];
}
那奏效了。
回答者: 亨茨切尔