简体   繁体   English

如何使for循环参数动态化

[英]How can i make the for loop parameters dynamic

for ($i=40; $i>=30; $i--)  //code will display data for top x row
for ($i=1; $i<=9; $i++)    //code will display data for left y column
for ($i=29; $i>=21; $i--)  //code will display data for bottom x row
for ($i=30; $i>=39; $i++)  //code will display data for right y column

These 4 loops all do the same thing. 这4个循环都做同样的事情。 In my index.php im using "include" to get the 4 loops that are in 4 different files. 在我的index.php中使用“include”来获取4个不同文件中的4个循环。 How can I make the for loop dynamic? 如何使for循环动态化?

Algoritihm: Algoritihm:

$i = (40,1,29,30)  <--will be any of those 4
$maxlow = (30,9,21,39) 
$check =(>,<)     <--value depends on whether $i > or < $maxlow
$icrement =  (--,++)   <-- if $check is > then decrease, otherwise increment

for ($i; $i($check)=$maxlow; $i($increment) <---what i am trying to do
// $step is either 1 (incrementing) or -1 (decrementing)
foreach (range($begin, $maxlow, $step) as $i) {

}
$low = [40,1,29,30](rand(0,3);
$high = [30,9,21,39](rand(0,3);
$modifier = ($low > $high) ? -1 : 1;

for($i = $low; ($i * $modifier) < ($high * $modifier); $i += $modifier)
{
  doStuff();
}

Settings for given loop: 给定循环的设置:

$diff = -1;
$start = 40;
$stop = 30 + $diff;

The loop itself, always like this: 循环本身,总是这样:

for ($i = $start; $i != $stop; $i += $diff)

why not just use for with switch inside, like this: 为什么不只是用于内部开关,像这样:

for ($i=1; $i >=39; $i++) {
    switch($i) {
       case ($i>=1 && $i<=9):
       break;
       ...
       ...
       case ($i>40):
       //do something
       break;
    }

}

It will be much more readable, and easier to understand/edit in future. 它将更具可读性,并且将来更容易理解/编辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM