【发布时间】:2010-12-02 19:24:10
【问题描述】:
如何在 for 循环中每 5 个结果执行一次操作?
基本上我只是想模拟一个有 5 列的表格。
【问题讨论】:
如何在 for 循环中每 5 个结果执行一次操作?
基本上我只是想模拟一个有 5 列的表格。
【问题讨论】:
你可以使用模运算符
for(int i = 0; i < 500; i++)
{
if(i % 5 == 0)
{
//do your stuff here
}
}
【讨论】:
for ($i = 0; $i < 500; $i += 5) { ... }。
(i%5==0) 将在第一次、第六次、第十一次……通过时运行。使用(i%5==4) 在第五、第十、第十五……传球时触发。
对于 HTML 表格,试试这个。
= $i; ?>
【讨论】:
正如所指出的,可以使用带模数的条件。您也可以使用嵌套循环来做到这一点。
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
}
如果 n 保证是 5 的倍数,或者您不关心在最后触发一个额外事件,则此方法效果很好。否则,您必须将其添加到末尾,这会使它变得不那么漂亮。
//If n is not guaranteed to be a multiple of 5.
while(i < n)
{
//loop body
++i;
}
并将 int limit = n - 5 更改为 int limit = n - 5 - (n % 5)
【讨论】:
另一种变化:
诠释 j = 0; for(int i = 0; i = 5) { j = 0; //在这里做你的事情 } }我很老土,我记得除法需要很长时间。使用现代 CPU,这可能并不重要。
【讨论】:
这可以在 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;
}
}
}
【讨论】:
// That's an easy one
for($i=10;$i<500;$i+=5)
{
//do something
}
【讨论】:
$i 每次运行都会增加 5。