Php 跳过foreach循环中的索引
我见过在foreach中,如果我<25等,只命中某些数字的选项,但我想知道如何最好地完全跳过字符串索引 我有一个运行完美的循环,我不想改变它在做什么,我只想省略一行,它的索引是'employee' 我已经尝试了下面的方法,但它似乎不起作用,因为我的if语句中出现了语法错误Php 跳过foreach循环中的索引,php,loops,indexing,Php,Loops,Indexing,我见过在foreach中,如果我
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++;
}
}
试用
继续
范例
考虑到您想让环体保持圆滑,这里有一种可能的非破坏性方法。在每次迭代中不检查任何东西也可以节省一点性能损失。请参阅注释以了解逐步的解释
<?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)
*/
使用循环中的索引可以像这样忽略employee部分
foreach ($arr as $string_index => $row) {
if(strtolower($string_index) !== 'employee'){
//Content
}
}
我假设变量的其余部分是在其他地方定义的,并且只包含索引部分,因为它有点混乱。如您所见,在“As”之后可以使用$variable,后跟“=>”,然后是$individual\u行
第一个变量是数组的索引,而第二个变量是行
快乐编码一个$row看起来怎么样?员工价值在哪里?如果!数组_key_存在'employee',$arr{…}假设你说employee是你想要避免的一个键。如果密钥存在但可以为空,您可以使用ifempty$arr['employee']{Agree。如果您想跳过多个,您可以添加一个$blacklist,并在If中询问您在数组$row['id'],$blacklist中是否继续。-做得很好:这很有意义,谢谢。我现在看到有几种不同的方法,但这给了我最好的结果
foreach ($arr as $string_index => $row) {
if(strtolower($string_index) !== 'employee'){
//Content
}
}