douxian4323 2015-05-05 16:33
浏览 77
已采纳

PHP使用while和嵌套for循环错误地循环输出

Attempting to generate table columns and rows based on input. With smaller numbers it appears to work appropriately, for example inputting 2 rows and 3 cols. But when inputting slightly larger numbers like 5 for rows will output an incorrect amount of rows sometimes looping indefinitely.

if(isset($_POST['submit'])) {

    $rows = (int)$_POST['row_num'];
    $cols = (int)$_POST['col_num'];
    $n = 1;
    $e = 0;

    echo '<table id="">';

    while(($e < $rows) && ($e < $cols)) {

        for($i = 0; $i < $rows; $i++) {
            echo '<tr>';

            for($i = 0; $i < $cols; $i++) {
                echo '<td><input type="text" name="field_' . $n . '"></td>';
                $n++;
            }

            echo '</tr>';
        }

        $e++;
    }

    echo '</table>';
}
  • 写回答

2条回答 默认 最新

  • doumingchen3628 2015-05-05 16:38
    关注

    Firstly, you don't need the While loop, it's pointless and probably causing issues.

    Secondly, you're using $i for both your rows and your columns, you can't use the same variable for both. Use $i for one and $j for the other. This should work:

    if(isset($_POST['submit'])) {
    
        $rows = (int)$_POST['row_num'];
        $cols = (int)$_POST['col_num'];
        $n = 1;
    
        echo '<table id="">';
    
        for($i = 0; $i < $rows; $i++) {
            echo '<tr>';
    
            for($j = 0; $j < $cols; $j++) {
                echo '<td><input type="text" name="field_' . $n++ . '"></td>';
            }
    
            echo '</tr>';
        }
    
        echo '</table>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 matlab计算中误差
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊