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条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改