【问题标题】:how to run for loop conditionally, with certain values omitted , PHP如何有条件地运行for循环,省略某些值,PHP
【发布时间】:2016-03-07 18:07:09
【问题描述】:

我想运行这个循环并将值放在 for 循环中定义的新变量中

stage= stage1, stage3, stagexx

for ($i=0;$i<=count($name);$i++) {
$current[$i]  = $count[$i];
$stage = array_replace($stage, $stage1);
} 

我必须为我的脚本运行几个 for 循环。

上面的for循环
我想首先为所有 count($name) 运行它,如果满足某些条件。

示例:


我想
省略 $name[3] 并再次运行循环。
或者
省略 $name[6] 并再次运行循环。将新值放入

$current[$i]  = $count[$i];
$stage = array_replace($stage, $stage1); 

结果值:

最后,我想根据省略的值获取下面提到的变量的新值,当我省略任何值时,变量会很好地改变它们的值。

$current[$i]  = $count[$i];
$stage = array_replace($stage, $stage1); 

**omit $name[3]** 
  $current[$i]  = $count[$i];
    $stage = array_replace($stage, $stage4);

**omit $name[xx]** 
  $current[$i]  = $count[$i];
    $stage = array_replace($stage, $stagexx);  

编辑:

如果我省略了值,for 循环的新面貌会是什么。

例如:

如果 ($i 3 ) 我想再次运行 for 循环,并省略 value = 3

for ($i=0;$i<=count($name);$i++) {
    $current[$i]  = $count[$i];
    $stage = array_replace($stage, $stage1);
    } 

我想知道如何用省略的值再次编写 for 循环?

【问题讨论】:

    标签: php mysql for-loop


    【解决方案1】:

    如果您想在某些情况下跳过循环内的执行并继续循环,您应该使用 continue 语句。例如:

    <?php
        for ($i = 0; $i < 5; ++$i) {
            if ($i == 2)
                continue;
            print "$i\n";
        }
    ?>
    

    【讨论】:

      【解决方案2】:

      我发现这个问题有点难以理解。您是否可以将此代码块放入函数中并参数化该函数,以便您拥有(例如)要省略的索引列表?

      function yourLoopFunction($namesArr, $omitIndicesArr){
          $current = array();
      
          ... // where stage, stage1 come from
      
          for ($i=0; $i < count($name); $i++) {
              if (!in_array($i, $omitIndicesArr){
                  $current[$i]  = $count[$i];
                  $stage = array_replace($stage, $stage1);
              }
          }
      
          return $current;
      }
      

      【讨论】:

        【解决方案3】:

        为此:

        **omit $name[3]** 
          $current[$i]  = $count[$i];
        

        排除它

        **omit $name[3]** 
          if ($i<>3)  $current[$i]  = $count[$i];
        

        没有理由不工作。

        编辑:您不修改 FOR 循环。您在其中设置条件:

        for ($i=0;$i<=count($name);$i++) {
            if ($i<>3)  $current[$i]  = $count[$i];  //only run this if it's not=3
            //$current[$i]  = $count[$i];  
            $stage = array_replace($stage, $stage1);
            } 
        

        【讨论】:

        • 有了这个,它不应该影响 $i=3 的值,并且应该保存其余的新值..你的代码是这样吗???
        • 它没有设置 $i。它只是检查它的状态。所以这不会破坏任何东西。此外,您可以将该省略设置为您想要的任何内容。在本例中,它被硬编码为“3”。您可以在开始循环之前将其设置为变量。省略你想要的任何一个。
        • for 循环 for ($i3 ) 的格式是什么。在循环的第一个实例中,我将收集所有值,然后运行一个带有省略值的新循环。如何编写新的 for 循环,以便我不读取 ($i3 ) 的值,省略一个???
        • 查看我的答案的编辑。我真的不明白你想做什么。我只是想根据你的要求给你一个想法。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多