dozug64282 2018-05-05 09: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 09: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部