douqujin2767 2018-09-04 10:31
浏览 37

如何使这个循环计数从1-8?

I'm creating tables with 4 rows and 2 columns using this for loop:

   $row = 4; //Dynamic number for rows
   $col = 2; // Dynamic number for columns


   for($i=0;$i<$row;$i++){
      for($j=0;$j<$col;$j++){
        echo $i+$j.'</br>';
      }

  }

However, I cannot seem to get it to output 1-8 in numbers sequentially.

Would be grateful is someone knows how to do this?

Cheers

K

  • 写回答

2条回答 默认 最新

  • donglu5235 2018-09-04 11:01
    关注

    You just need to do a bit of maths on the number output. As each value of $i represents a set of columns (each being $col long), I use $i*$col, add the column ($j), but as $j starts at 0, I just add 1 for the final value...

    $row = 4; //Dynamic number for rows
    $col = 2; // Dynamic number for columns
    
    for($i=0;$i<$row;$i++){
        for($j=0;$j<$col;$j++){
            echo (($i*$col)+$j+1).'<br />';
        }
    }
    

    Which outputs...

    1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大