php - 如何输出自定义的while循环php
问题描述
我想在我的 while 循环中使用计数器作为自定义,假设我们有一个 while 循环 < 21 我试图输出类似这样的结果:
1,2,
3,4,
5,6,7,
8,9,
10,11,
12,13,14,
15,16,
17,18,
19,20,21
我尝试编写这些代码
<?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;
但是输出是这样的
1
2,3,4,
5
6,7,8,
9
10,11,12,
13
14,15,16,
17
18,19,20,
解决了
@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;
解决方案
你可以尝试这样的事情,它应该像你描述的那样工作:
$counter = 1;
for($i = 1; $i < 21; $i++){
echo $i . ',';
if($counter % 6 == 0){
echo ++$i . ',<br>';
}
elseif($counter % 2 == 0){
echo '<br>';
}
$counter++;
}
推荐阅读
- git - 如何将两个存储库加入一个存储库 GIT
- python - zlib的结果在python和php之间有不同的尾巴
- python - 如何转换日期(“\n”问题)
- angularjs - 使用正则表达式进行角度搜索
- tensorflow - 零损失会影响反向传播更新吗
- macos - 通过 Ansible playbook 运行 docker-compose 命令时出错
- html - 如何使子元素位于父元素之后,但不在主容器之上
- elasticsearch - 将 Kafka Connect 与 Azure 事件中心和/或 AWS Kinesis/MSK 一起使用,将数据发送到 ElasticSearch
- php - WooCommerce 相关产品:行
- reporting - 另一个表中的 Quicksight 查找值