简体   繁体   English

如何输出自定义的while循环php

[英]How to output a custom while loop php

I want to use a counter as a custom in my while loop, let's say we have a while loop < 21 I am trying to output something like this results: 我想在我的while循环中使用一个计数器作为自定义,假设我们有一个while循环<21,我正在尝试输出类似以下结果的结果:

1,2,
3,4,
5,6,7,
8,9,
10,11,
12,13,14,
15,16,
17,18,
19,20,21

I tried with writing these codes 我尝试编写这些代码

<?php 

$counter = 1;

while ($counter <21) : 
    if( $counter == 1 || ($counter-1)%4 == 0 ) { 
        echo $counter."<br>";
    } 

    if( $counter == 2 || ($counter-2)%4 == 0 ) { ?>
    <div class="others">
    <?php } 
    if( $counter != 1 && ($counter-1)%4 != 0 ) { 
        echo $counter.',';
    }
    if( $counter%4 == 0 ) { ?>
        </div>
    <?php } 
    $counter++;
endwhile; 

But the output is like this 但是输出是这样的

1
2,3,4,
5
6,7,8,
9
10,11,12,
13
14,15,16,
17
18,19,20,

SOLVED 解决了


@cannon gives a solution that works perfectly, but I want use the loop for calling database posts so that is why I resolve the problem... @cannon提供了一个完美的解决方案,但是我想使用循环来调用数据库帖子,因此这就是我解决问题的原因...

<?php
$counter = 1;
$module =  7;
$i = 2;
$arr = [];
while ($counter <22) : 
    if( $counter == 1 || ($counter-1)% $module == 0  ) { 
        echo $counter.',';
    } 
    if(  $counter == 2  || ($counter-2)% $module    == 0 ) { 
        echo $counter.',<br>';
    } 
    if( $counter == 3 || ($counter-3)% $module == 0  ) { 
        echo $counter.',';
    } 
    if(  $counter == 4  || ($counter-4)% $module    == 0 ) { 
        echo $counter.',<br>';
    }
    $i = $i + $module;
    $arr[] = $i;
    if(!in_array($counter,$arr)){
        if( $counter == 5 || ($counter-5)% $module == 0 ) { 
            } 
        if( $counter != 1 && $counter != 2  && $counter != 3 && ($counter-1)% $module != 0  
        && $counter != 4  && ($counter-3)% $module != 0 && ($counter-4)% $module != 0  ) { 
            echo $counter.',';
        }
        if( $counter% $module == 0 ) { 
            echo '<br>';
        }
    } 
    $counter++;
endwhile; 

You could try something like this, and it should work just as you described: 您可以尝试这样的操作,它应该可以像您描述的那样工作:

$counter = 1;
for($i = 1; $i < 21; $i++){
    echo $i . ',';

    if($counter % 6 == 0){
        echo ++$i . ',<br>';
    }
    elseif($counter % 2 == 0){
        echo '<br>';
    }
    $counter++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM