【问题标题】:Skipping an index in foreach loop在 foreach 循环中跳过索引
【发布时间】:2021-02-25 14:08:15
【问题描述】:

我已经看到在 foreach 中只命中某些数字的选项(如果 i

我有一个完美运行的循环,我不想改变它正在做的事情,我只想省略索引为“员工”的一行

我已经尝试了以下方法,但它似乎不起作用,因为我的 if 语句出现语法错误

foreach ($arr as $row) {
  if($arr[] !== 'employee'){
        for ($i = 0; $i < count($colstrs); $i++) {
            $cellstr = $colstrs[$i] . $xrow;
            $ows->setCellValue($cellstr, $row[$i]);
            $ows->getStyle($cellstr)->getNumberFormat()->setFormatCode($this->numfmt);
        }
        $this->setFillColors($xrow);            
        $xrow++;
   }
}

【问题讨论】:

  • $row 长什么样子? employee 值在哪里?
  • if(!array_key_exists('employee', $arr)) { ... } 假设您说员工是您要避免的关键。如果密钥存在但可以为空,您可以使用if(empty($arr['employee'])) {

标签: php loops indexing


【解决方案1】:

像这样使用循环中的索引来忽略员工部分。

foreach ($arr as $string_index => $row) {
  if(strtolower($string_index) !== 'employee'){
    //Content
  }
}



     

我假设您的变量的其余部分是在其他地方定义的,并且只包含索引的部分,因为它有点令人困惑。如您所见,在“as”之后,您可以使用 $variable 后跟“=>”,然后是 $individual_row。

第一个变量是数组的索引,而第二个变量是行。

【讨论】:

    【解决方案2】:

    考虑到您希望保持循环体完整,这是一种可能的非破坏性方法。在每次迭代中不检查任何内容也可以为您节省一点性能损失。请参阅 cmets 了解分步说明。

    <?php
    
    // Sample array. We'll be filtering out the first element ('a').
    $a = ['a' => 123, 'b' => 2, 'c' => 'foo', 'd' => 'bar', 'abc' => 'def', 'def' => 789];
    
    // Use array_filter() to copy the array on certain condition ($key !== 'a').
    // Passing ARRAY_FILTER_USE_KEY will only pass the key to the callback, saving some memory.
    // The original array is left untouched.
    foreach (
        array_filter($a, function($key) { return $key !== 'a'; }, ARRAY_FILTER_USE_KEY)
        as $element
    )
    {
        var_dump($element);
    }
    
    /* Outputs:
    int(2)
    string(3) "foo"
    string(3) "bar"
    string(3) "def"
    int(789)
    */
    

    【讨论】:

    • 这很有道理,谢谢。我现在看到有几种不同的方法,但这给了我最好的结果
    【解决方案3】:

    尝试使用

    继续

    示例

             $rows = array(
                    [
                        'id'    => 2,
                        'name'  => 'Jon Doe'
                    ],
                    [
                        'id'    => 3,
                        'name'  => 'Smith'
                    ]
                );
                foreach ($rows as $row){
                    // if you are willing to skip who belongs id = 2
                    if ($row['id'] == 2)
                        continue;
                    
                    //Do your business logics
                    
                }
    

    【讨论】:

    • 同意。如果您想跳过多个,您可以添加一个$blacklist 并询问是否继续in_array($row['id'], $blacklist)。 - 做得很好:)
    猜你喜欢
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 2021-01-08
    相关资源
    最近更新 更多