dqw7121 2011-08-29 21:43
浏览 33
已采纳

foreach语句中的奇怪行为(额外循环)

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?

  • 写回答

1条回答 默认 最新

  • douhui1630 2011-08-29 21:47
    关注

    You are appending each row from mysql to your array and then output the whole array. Move the foreach loop out of your while:

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路