print_r数组返回嵌套数组

时间:2016-02-28 17:35:54

标签: php mysql arrays

我有以下脚本从我的代码中创建一个数组:

$roundstotal=mysql_query("SELECT id FROM calendar 
                          WHERE eventDate 
                          BETWEEN '$season_start' 
                              AND '$season_end' 
                              AND competition='$compId' 
                              AND tag!='T' 
                          ORDER BY eventDate ASC", $CONNECTW);
while($row = mysql_fetch_assoc($roundstotal)) {
    $roundsarray[]=$row;
}

当我尝试print_r它(作为print_r($roundsarray);)时,我得到以下内容,这不是我所见过的关于数组的所有文档都显示的内容。这可能就是为什么当我尝试使用数组中的数据时,我什么也得不到。

打印输出为:

Array ( [0] => Array ( [id] => 598 ) 
        [1] => Array ( [id] => 602 ) 
        [2] => Array ( [id] => 607 ) 
        [3] => Array ( [id] => 613 )  
        [4] => Array ( [id] => 619 )  
        [5] => Array ( [id] => 626 )  
        [6] => Array ( [id] => 633 )  
        [7] => Array ( [id] => 641 )  
        [8] => Array ( [id] => 648 )  
        [9] => Array ( [id] => 656 )  
        [10] => Array ( [id] => 660 )  
        [11] => Array ( [id] => 668 )  
        [12] => Array ( [id] => 675 )  
        [13] => Array ( [id] => 682 )  
        [14] => Array ( [id] => 688 )  
        [15] => Array ( [id] => 694 )  
        [16] => Array ( [id] => 699 ) )

这是对的吗?不应该是Array ([0] => 598 [1]=> 602等吗?

1 个答案:

答案 0 :(得分:2)

首先,mysql_*函数已被弃用了很多,所以不要使用它们。下面,我将使用mysqli_*函数回答。

其次,这是预期的行为,因为mysqli_fetch_assoc已经返回一个关联数组:

while($row = mysqli_fetch_assoc($roundstotal)) {
    // $row is an array of array("id" => 598); and so on
    $roundsarray[]=$row;
}

您需要的是

while($row = mysqli_fetch_assoc($roundstotal)) {
    $roundsarray[]=$row['id'];
}

然后$roundsarray数组看起来像你期望的那样:

Array (
    [0] => 598 
    [1] => 602 
    [2] => 607 
    [3] => 613
    // ... and so on
)