【发布时间】:2017-11-07 14:51:51
【问题描述】:
在使用 str_getcsv 读取 CSV 文件并为其分配键时,我很难摆脱这个未定义的偏移量通知。
我已经尝试过isset 和array_key_exists,这在其他线程中已经提到过。 isset 确实解决了未定义的索引通知,但我无法删除未定义的偏移通知:
$file = file("lookup.csv",FILE_SKIP_EMPTY_LINES);
$csv = array_map("str_getcsv",$file, array_fill(0, count($file), ';'));
$keys = array_shift($csv);
foreach ($csv as $i=>$row) {
$csv[$i] = array_combine($keys, $row);
}
$numberOfRows = count($csv);
$numberOfColumns = count(current($csv));
for ( $i = 0; $i <= $numberOfRows; $i ++ ) { // first loop to run thru to find correct sku template name in csv file
if ( $csv[$i]['sku'] === $sku ) { // if sku matches // Getting Undefined offset on this line
for ( $j = 0; $j <= $numberOfColumns; $j++) { // second loop to create variables from header line
${$keys[$j]} = isset($csv[$i][$keys[$j]]) ? $csv[$i][$keys[$j]] : ''; // // Getting 2 Undefined offset notices on this line
}
}
}
有问题的 CSV 文件确实有一些空白单元格。那些空白单元格将被保留(我对此无能为力)。
请谁能指出我正确的方向?非常感谢任何帮助,谢谢!
【问题讨论】:
-
试试这个 $file = file('lookup.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);