0

我正在上传一个包含 10 列的 CSV 文件/报告,但在 CSV 文件的末尾有几行仅提供有关报告的详细信息,例如

生成者:XXX

公司名称

报告运行@ 2019-03-14

当我加载数组时,键只是数字(从 0 到 9),但我想让它成为基于列标题的关联数组。不幸的是,这不适用于最后几行,因为数组维度不同(1 vs 10)

这是我的代码:

$csv = array_map('str_getcsv', file($_FILES['file']['tmp_name']));
array_walk($csv, function(&$a) use ($csv) {
    if(count($csv[0]) != count($a)) {
        $a = null; // Remove the array
    } else {
        $a = array_combine($csv[0], $a); 
    }
});
array_shift($csv); # remove column header

当我这样做$a = null;时,通过将其替换为NULL. 当我遍历数组时,我会if(is_null($row)) continue;忽略该NULL元素。有没有办法真正删除数组?

4

2 回答 2

2

I think it's more straightforward without array_walk. array_walk is just going to apply the function to every member of the array. Setting it to null doesn't mean it's gone, it just has a null value as you've seen. If you really want it gone, you need to unset it. Just refer to $csv by key and unset the ones you don't want.

$keys = array_shift($csv);
$expected_count = count($keys);
foreach ($csv as $index => $values) {
    if (count($values) == $expected_count) {
        $csv[$index] = array_combine($keys, $values);
    } else {
        unset($csv[$index]);
    }
}
于 2019-03-14T19:41:23.347 回答
0

Array_filter($csv); 之后将从您的数组中删除所有 null/false/0。

因此,编写一个自定义函数来仅删除 null 可能更聪明。

于 2019-03-14T19:37:48.817 回答