难以从数组的 foreach 中删除数组中的记录

Difficulty deleting record from array within a foreach of the array

所以我有一个从 csv 文件生成的多维数组 $lines。它填充了如下所示的记录:

 [0] => 038572 
 [1] => L 
 [2] => Testing
 [3] => BQ
 [4] => 
 [5] => 52.40308886
 [6] => -0.19266809
 [7] => 01/12/2018
 [8] => 
 [9] => B
 [10] => 
 [11] => 5
 [12] => 
 [13] => 
 [14] => 
 [15] => 
 [16] => ldn d 5BQ
 [17] => 038572
 [18] =>

我也有全为空的记录接受一位,其中有:

[16] => ,

这是我要取消设置的这些记录。所以我尝试了以下方法:

foreach($lines as $element) {
    if ($element[16] == ",") {
        unset($element);
    }
}

但是当我 print_r 数组 $lines 时,我仍然可以看到那些部分为空的记录。

您正在循环内处理临时副本,因此当您取消设置 $element 时,它对原始 $lines 数组没有影响。您可以使用引用,或从原始数组中取消设置值:

foreach ($lines as $index => $element) {
    if ($element[16] === ',') {
        unset($lines[$index][16]);
    }
}

或者像这样:

for ($i = 0, $_i < count($lines); $i < $_i; $i++) {
    if ($lines[$i][16] === ',') {
        unset($lines[$i][16]);
    }
}

或其他十几种方法中的任何一种...

请注意,在此处使用 unset() 实际上会从数组中删除该项目,这可能会使您的列不对齐,具体取决于您编写代码的方式。您可能不想取消设置,而是将其设置为空。

您不能修改作用于 $element 的 $lines 的原因是您需要 通过引用传递它

In order to be able to directly modify array elements within the loop precede $value with > &. In that case the value will be assigned by reference. read http://php.net/manual/en/control-structures.foreach.php)

但在你的情况下,我会创建第二个数组来存储有效记录:

$valid_records = [];
$exclude = [" ", ", "];
foreach($lines as $element) {
    if (!in_array($element, $exclude)) {
        array_push($valid_records, $element);
    }
}
$lines = $valid_records;

它可能不那么优雅和节省内存,但不要乱用unset

如果您正试图从数组中删除该空记录:

foreach( $lines as $key => $val ) {
    if( trim( $val[16] ) == ',' ) { // trim if there is any space with ','
        unset( $lines[$key] );
    }
}

print_r( $lines );