php 如何每 5 个结果执行一个操作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1500675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to perform an action every 5 results?
提问by John Boker
How can I perform an action within a forloop every 5 results?
如何在for每 5 个结果的循环中执行一个操作?
Basically I'm just trying to emulate a table with 5 columns.
基本上我只是想模拟一个有 5 列的表。
回答by John Boker
you could use the modulus operator
你可以使用模运算符
for(int i = 0; i < 500; i++)
{
if(i % 5 == 0)
{
//do your stuff here
}
}
回答by Steve
For an HTML table, try this.
对于 HTML 表格,试试这个。
<?php
$start = 0;
$end = 22;
$split = 5;
?>
<table>
<tr>
<?php for($i = $start; $i < $end; $i++) { ?>
<td style="border:1px solid red;" >
<?= $i; ?>
</td>
<?php if(($i) % ($split) == $split-1){ ?>
</tr><tr>
<?php }} ?>
</tr>
</table>
回答by redcayuga
Another variation:
另一种变体:
int j=0;
for(int i = 0; i < 500; i++)
{
j++;
if(j >= 5)
{
j = 0;
//do your stuff here
}
}
I'm old fashioned, I remember when division took a long time. With modern cpus it probably doesn't matter much.
我是老式的,我记得分裂需要很长时间。使用现代 CPU,它可能无关紧要。
回答by patros
It's possible to use a condition with a modulus, as pointed out. You can also do it with nesting loops.
正如所指出的,可以使用带模数的条件。您也可以使用嵌套循环来做到这一点。
int n = 500;
int i = 0;
int limit = n - 5
(while i < limit)
{
int innerLimit = i + 5
while(i < innerLimit)
{
//loop body
++i;
}
//Fire an action
}
This works well if n is guaranteed to be a multiple of 5, or if you don't care about firing an extra event at the end. Otherwise you have to add this to the end, and it makes it less pretty.
如果 n 保证是 5 的倍数,或者如果您不关心在最后触发额外的事件,这将很有效。否则,您必须将其添加到最后,这会使它变得不那么漂亮。
//If n is not guaranteed to be a multiple of 5.
while(i < n)
{
//loop body
++i;
}
and change int limit = n - 5 to int limit = n - 5 - (n % 5)
并将 int limit = n - 5 更改为 int limit = n - 5 - (n % 5)
回答by shdw
This works to get a live index within the foreach loop:
这可以在 foreach 循环中获取实时索引:
<?php
// Named-Index Array
$myNamedIndexArray = array('foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic', 'test' => 'one two', 'potato' => 'french fries', 'tomato' => 'ketchup', 'coffee' => 'expresso', 'window' => 'cleaner', 'truck' => 'load', 'nine' => 'neuf', 'ten' => 'dix');
// Numeric-Index Array of the Named-Index Array
$myNumIndex = array_keys($myNamedIndexArray);
foreach($myNamedIndexArray as $key => $value) {
$index = array_search($key,$myNumIndex);
if ($index !== false) {
echo 'Index of key "'.$key.'" is : '.$index.PHP_EOL;
if (($index+1) % 5 == 0) {
echo '[index='.$index.'] stuff to be done every 5 iterations'.PHP_EOL;
}
}
}
回答by Jose
// That's an easy one
for($i=10;$i<500;$i+=5)
{
//do something
}

