dozug64282 2018-05-05 17:21
浏览 11
已采纳

嵌套循环PHP

i have code :

<?php
$number =9;
$number2 = $number / 2;
    for ($b=0; $b<=$number2; $b++){
        for ($i=$number; $i>=1; $i--){
            echo $i;
        }
        echo "<br/>";
        for ($a=1; $a<=$number; $a++)
        {
        echo $a;
    }
    echo "<br/>";
}
?>

I want the result like this .

987654321
123456789
987654321
123456789
987654321
123456789
987654321
123456789
987654321

why if i put odd number like 9 , why always the result 10 loop ?

  • 写回答

2条回答 默认 最新

  • dqpdb82600 2018-05-05 17:39
    关注

    You have two loops in a loop, therefore you'll always get an even number of lines.

    You don't actually need that structure, see:

    $number=9;
    $k=0;
    $sum=1;
    for($i=1; $i<=$number; $i++) {
        for($j=1; $j<=$number; $j++) {
            $k+=$sum;
            echo $k;
        }
        echo '<br>';
        //Sum once again so in the next iteration $k is 0 or 10
        $k+=$sum;
        //Invert the sign of $sum so in the next iteration it substracts, and then adds, and so on
        $sum*=-1;
    }
    

    Also note that going from 0 to $number inclusive (lower or equal comparation) you'll get one iteration more (from 0 to 9 there are 10 whole numbers).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错