我怎样才能增加一个值1,每50次foreach循环运行

问题描述 投票:-5回答:4

我怎样才能在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 


}
?>
php foreach increment
4个回答
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;
}
}

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
投票

我不打算提供完整的答案,因为我不想鼓励这样的问题。但是,如果你真的被卡住了,只为你的想法,你将需要两个变量,一个将递增,每次循环运行,另一个将检查第一变量和当第一个变量是由50整除将只得到增加。


-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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.