douwei3863 2012-08-21 01:23
浏览 68
已采纳

循环遍历数组php中的每个第三个值

I am sure I am making this way more complicated than it is...

I have an array of values, lets just say they are numbers for now. I want to display them on a page in 3 columns. So I made 3 loops, one for each column. The first loop I want to loop every 3rd value, starting at index 0. The second loop should start at index 1 and do every third. And the third loop should start at index 2 and loop through every third.

This is what I wrote, which seems to work if you only have 3 things in the array, and I'm sure it's overly complicated.

Thanks

 <div class="span4 column">
        <?php for ($i = 0; $i <= count($articles_for_board)/3; $i = $i+2):?>
            stuff in here
            </div>
        <?php endfor; ?>
    </div>
    <div class="span4 column">
        <?php for ($i = 1; $i <= (count($all_boards)/3)+1; $i = $i+2):?>
            stuff in here
            </div>
        <?php endfor; ?>
    </div>
    <div class="span4 column">
        <?php for ($i = 2; $i <= (count($all_boards)/3)+2; $i = $i+2):?>
            stuff in here
            </div>
        <?php endfor; ?>
    </div>

So basically, the first column would hold array index 0, 3, 6... second column would hold 1, 4.. etc third column would hold 2, 5, 8...

THanks

  • 写回答

1条回答 默认 最新

  • douliao7354 2012-08-21 01:29
    关注

    With a for-loop, you don't need to worry so much about all that bounds checking. It's a lot simpler than you think it is:

    for ($i = 0; $i < count($all_boards); $i += 3)
    

    This loop increments by three every iteration — that is, it gets every third member — and it stops as soon as it exceeds the length of $all_boards.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款