foreach 循环每运行 50 次,如何将值递增 1
How can I increment by a value by 1 for every 50 times a foreach loop runs
如何在 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
}
?>
您可以使用另一个计数器来检查您何时完成了 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++;
}
}
?>
我不会提供完整的答案,因为我不想鼓励这样的问题。但是,如果你真的被卡住了,这只是你的一个想法,你将需要两个变量,一个会在每次循环运行时递增,另一个会检查第一个变量,并且只有当第一个变量被 50 整除时才会递增。
$counter = 1;
$loop_ctr = 0;
$increment_by = 1;
foreach($numbers as $num)
{
$counter+=$increment_by;
$loop_ctr++;
if($loop_ctr == 50)
{
$increment_by = 2;
}
}
<?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;
}
}
如何在 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
}
?>
您可以使用另一个计数器来检查您何时完成了 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++;
}
}
?>
我不会提供完整的答案,因为我不想鼓励这样的问题。但是,如果你真的被卡住了,这只是你的一个想法,你将需要两个变量,一个会在每次循环运行时递增,另一个会检查第一个变量,并且只有当第一个变量被 50 整除时才会递增。
$counter = 1;
$loop_ctr = 0;
$increment_by = 1;
foreach($numbers as $num)
{
$counter+=$increment_by;
$loop_ctr++;
if($loop_ctr == 50)
{
$increment_by = 2;
}
}
<?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;
}
}