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.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里