我如何在foreach循环中每运行50次就增加一个值。
<?php
$counter = 1;
foreach ($numbers as $num) {
//For the first 50 times the loop runs, $counter = 1. For every 50 runs, increment by 1
$counter = 1;
//if loop has run more than 50 times, increment $counter to 2
}
?>
答案 0 :(得分:1)
您可以使用另一个计数器检查完成50次迭代的时间
<?php
$counter = 1;
$MiniCounter = 0;
foreach ($numbers as $num)
{
// Pre-increment since $MiniCounter starts by 0
if (++$MiniCounter >= 50) // using >= 50 because, who knows, $MiniCounter may jump magically from 49 to 51
{
$MiniCounter = 0; //reset the mini counter
$counter++;
}
}
?>
答案 1 :(得分:0)
<?php
$counter = 0;
$value = 50; // Intial position
$numbers = 230 // Lets say you have total 230 iterations.
for ($i = 0 ; $i <= $numbers ; i++)
{
if($i == $value) // if 50 counter is increased and we are setting the value to 100
{
$counter += 1;
$value = $value * 2;
}
}
答案 2 :(得分:-1)
我不想提供完整的答案,因为我不想鼓励这样的问题。但是,如果您确实陷入困境,那么您将需要两个变量,一个变量将在每次循环运行时递增,另一个变量将检查第一个变量,并且仅在第一个变量可被50整除时才会递增。 >
答案 3 :(得分:-1)
$counter = 1;
$loop_ctr = 0;
$increment_by = 1;
foreach($numbers as $num)
{
$counter+=$increment_by;
$loop_ctr++;
if($loop_ctr == 50)
{
$increment_by = 2;
}
}