dpfw3607 2016-12-27 15:10
浏览 146
已采纳

PHP:如何将foreach-loop拆分为3个部分?

I have a little problem on my website. I have a Blog and every article is in one list. Now I want to split this one list into 3 lists.

My Problem:

<ul class="row-3">
<?php $i = 1; foreach($posts as $post): ?>
    <?php if($i % 3 == 0): ?>
        <?php echo "$article" ?>              
    <?php endif; $i++; ?>
<?php endforeach ?>
</ul>

<ul class="row-2">
<?php $i = 1; foreach($posts as $post): ?>
    <?php if($i % 2 == 0): ?>
        <?php echo "$article" ?>              
    <?php endif; $i++; ?>
<?php endforeach ?>
</ul>

If I make it like this will every third loop go into the third list and every second loop into the second list. But the problem is:

Article 5 and 10 will be in both lists...

So I have to split the whole foreach-loop into 3 parts that a counter count until 3 and then if its at 3 it changes to 0 again so I can put every 1 into the first list every 2 into the second and every 3 into the third list but I have absolutely no idea how I can solve this.

I hope you guys can help me a bit and I'm sorry for my bad english..

Thanks a lot.

  • 写回答

2条回答 默认 最新

  • dpw63348 2016-12-27 15:17
    关注

    I'm not surer that this will work with your ordering, but array_chunk, https://secure.php.net/manual/en/function.array-chunk.php, may do what you want.

    This way you don't have to deal with the sharing a common multiple.

    If ordering is an issue, there is a comment on the array_chunk page which has some code that does an array_chunk_vertical. One of these two methods should get you what you need.

    Something like this untested code below:

    // Each group will be in it's own section array. $sections = array_chunk($posts, 2);

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

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面