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 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持