使用if-else语句对数组进行排序会使用数值创建新的和不需要的键

时间:2016-02-15 07:26:20

标签: php html arrays if-statement associative-array

为什么在尝试使用if-else语句对初始数组进行排序时,此代码会使用数值创建新键?

    <?php
 $url = file_get_contents("http://i.turner.ncaa.com/sites/default/files/external/test/scoreboard.json");
 $turnerNCAAJsonObject = json_decode($url,true);

for ($n = 0; $n <= count($turnerNCAAJsonObject); $n++) {
    if(isset($turnerNCAAJsonObject[$n][state]) && $turnerNCAAJsonObject[$n][state] == 'final') {
        echo "this is the final game";
    }elseif (isset($turnerNCAAJsonObject[$n][state]) && $turnerNCAAJsonObject[$n][state] == 'pre') {
        echo "this is a pre-game";
    }elseif ($turnerNCAAJsonObject[$n][state] == 'live') {
        $liveGames[] = array_push($liveGames, $turnerNCAAJsonObject[$n]);
    }
}
print_r($liveGames);

?>

1 个答案:

答案 0 :(得分:1)

当您使用$liveGames[]分配新密钥时,请替换此行:

$liveGames[] = array_push($liveGames, $turnerNCAAJsonObject[$n]);

用这个:

array_push($liveGames, $turnerNCAAJsonObject[$n]);