简体   繁体   English

遍历数组php中的每三个值

[英]loop through every third value in array 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. 我想在3列的页面上显示它们。 So I made 3 loops, one for each column. 所以我做了3个循环,每列一个。 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. 我想要的第一个循环是从索引0开始的每个第3个值。第二个循环应从索引1开始并且每三个执行一次。 And the third loop should start at index 2 and loop through every third. 第三个循环应从索引2开始,并每隔三分之一循环一次。

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. 这就是我写的内容,如果数组中只有3个元素,这似乎可以工作,而且我确信它过于复杂。

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... 所以基本上,第一列将保存数组索引0、3、6 ...第二列将保存数组1、4 ..等等,第三列将保存数组2、5、8 ...

THanks 谢谢

With a for-loop, you don't need to worry so much about all that bounds checking. 使用for循环,您不必担心所有边界检查。 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 . 该循环在每次迭代时增加三(即,它获得每三个成员),并在超过$all_boards的长度时$all_boards

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM