用于基于当前值的循环步骤

时间:2018-09-16 17:09:24

标签: php

我已经设置了上面显示整数的循环。

我希望能够根据值($i)设置步骤

$min = 100;
$max = $1000;

$step_values = array(
    900 => 100,
    100000 => 1000
);

for($i = $min; $i <= $max; $i += 100) {
    echo '<option value="'.$i.'">'.$i.' Credits (&pound;'.number_format($credit_cost,2).' = &pound;'.number_format(($credit_cost * $i)).')</option>';
}

当前循环以100为步长,但是我想基于$step_values的当前值,以$i数组中的值为步长

例如,对于数组而言,对于值为900及以下的值,该步骤为100,对于数组为10000及以下的值,该步骤为1000,但是我不确定如何执行' ”。

1 个答案:

答案 0 :(得分:2)

由于您每次都需要搜索增量,因此我将增量移到了循环内,并且在每个循环中,它都会浏览步进值列表并对照当前值进行检查...

$min = 100;
$max = 10000;    // Remove the $ and for testing I've increased this

$step_values = array(
    200 => 100,
    300 => 200,
    2500 => 500,
    5000 => 1000,
    10000 => 2000    
);
$credit_cost = 1;   // Test value
for($i = $min; $i <= $max;) {
    echo '<option value="'.$i.'">'.$i.' Credits (&pound;'.number_format($credit_cost,2).' = &pound;'.number_format(($credit_cost * $i)).')</option>';
    foreach ( $step_values as $limit => $increment )    {
        if ( $i <= $limit )  {
            $i+=$increment;
            break;
        }
    }
}

这将输出...

<option value="100">100 Credits (&pound;1.00 = &pound;100)</option>
<option value="200">200 Credits (&pound;1.00 = &pound;200)</option>
<option value="300">300 Credits (&pound;1.00 = &pound;300)</option>
<option value="500">500 Credits (&pound;1.00 = &pound;500)</option>
<option value="1000">1000 Credits (&pound;1.00 = &pound;1,000)</option>
<option value="1500">1500 Credits (&pound;1.00 = &pound;1,500)</option>
<option value="2000">2000 Credits (&pound;1.00 = &pound;2,000)</option>
<option value="2500">2500 Credits (&pound;1.00 = &pound;2,500)</option>
<option value="3000">3000 Credits (&pound;1.00 = &pound;3,000)</option>
<option value="4000">4000 Credits (&pound;1.00 = &pound;4,000)</option>
<option value="5000">5000 Credits (&pound;1.00 = &pound;5,000)</option>
<option value="6000">6000 Credits (&pound;1.00 = &pound;6,000)</option>
<option value="8000">8000 Credits (&pound;1.00 = &pound;8,000)</option>
<option value="10000">10000 Credits (&pound;1.00 = &pound;10,000)</option>

让我知道是否有任何问题。