如何从一个while循环访问一个数组

时间:2015-08-20 18:31:49

标签: php arrays

我希望有人可以帮助我。我使用数组存储从数据库中提取的值,但我想知道如何从while循环外部访问它们?

$lecturers_temp = array(array());
$i = 0;

$q2 = "SELECT `uninum` FROM `availabilityindex` ORDER BY `availability`";

$result2 = @mysqli_query($dbcon,$q2);

while ($row2 = mysqli_fetch_array ($result2, MYSQLI_ASSOC)){
    $lecturers = $row2['uninum']; 
    $lecturers_temp = array(array());
    $lecturers_temp[$i][0] = $row2['uninum'];

    echo $lecturers_temp [$i] [0] . "<BR><BR>";
    $i++;

}

//when I try this I get an undefined offset error
echo $lecturers_temp [1] [0];

3 个答案:

答案 0 :(得分:2)

只需从$lecturers_temp = array(array());块中删除while代码即可。另外,为了简化数据,您可以使用一维数组:

$lecturers_temp = array();

$i = 0;

$q2 = "SELECT `uninum` FROM `availabilityindex` ORDER BY `availability`";

$result2 = @mysqli_query($dbcon,$q2);

while ($row2 = mysqli_fetch_array ($result2, MYSQLI_ASSOC)){
    $lecturers_temp[$i] = $row2['uninum'];

    echo $lecturers_temp[$i] . "<BR><BR>";
    $i++;
}

//when I try this I get an undefined offset error
echo $lecturers_temp [1];

答案 1 :(得分:1)

您收到该错误是因为您在while循环中重置了数组。摆脱while循环中的$lecturers_temp = array(array());,看看是否能得到你想要的结果。

答案 2 :(得分:0)

while循环中的$lecturers_temp = array(array());删除了存储在数组中的所有先前项。