foreach 语句中的奇怪行为(额外循环)
我有以下代码:
$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
)
)
由于某种我无法理解的原因,它给了我一些奇怪的循环,它返回第一行,然后是前两行,然后是前三行。
我做错了什么?
I have the following code:
$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);
And get the following output:
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
)
)
For some reason that I cannot fathom, its giving me some weird loop where it returns the 1st row, then the first two rows, then the first three rows.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将 mysql 中的每一行附加到数组中,然后输出整个数组。将 foreach 循环移出 while:
You are appending each row from mysql to your array and then output the whole array. Move the foreach loop out of your while: