我有以下代码:
$result = mysql_query("SELECT * FROM events",$db);
$rowcheck = mysql_num_rows($result);
$allevents = array();
echo "<br>Display events: ($rowcheck)";
$i = '0';
while ($row_user = mysql_fetch_assoc($result)){
$allevents[] = $row_user;
foreach ($allevents as $val) {
$eventID = $val['event_ID'];
echo "<br>$eventID";
echo "End foreach.";
} // end foreach events as val
echo "End While.";
} // end while
print_r($allevents);
获得以下输出:
Display events: (3)
ID 1 End foreach.End While.
ID 1 End foreach.
ID 2 End foreach.End While.
ID 1 End foreach.
ID 2 End foreach.
ID 3 End foreach.End While.
Array (
[0] => Array (
[event_ID] => 1
[eventtype] => 1
[eventlocation] => 1
[eventhostfamily] => 23
[eventturn] => 459
[char1] => 9
[char2] => 19
)
[1] => Array (
[event_ID] => 2
[eventtype] => 4
[eventlocation] => 1
[eventhostfamily] => 29
[eventturn] => 461
[char1] => 208
[char2] => 0
)
[2] => Array (
[event_ID] => 3
[eventtype] => 4
[eventlocation] => 1
[eventhostfamily] => 28
[eventturn] => 462
[char1] => 1
[char2] => 0
)
)
由于某些我无法理解的原因,它给了我一些奇怪的循环,它返回第一行,然后是前两行,然后是前三行。
我做错了什么?
答案 0 :(得分:2)
您将mysql中的每一行追加到数组中,然后输出整个数组。移动foreach循环:
while ($row_user = mysql_fetch_assoc($result)){
$allevents[] = $row_user;
echo "End While.";
} // end while
foreach ($allevents as $val) {
$eventID = $val['event_ID'];
echo "<br>$eventID";
echo "End foreach.";
} // end foreach events as val