0

我正在使用league/csv:^9.6(9.6.2)。

我需要解析具有大量列(150+)的 CSV 文件,并提取其中的少量(8)。这些列在偏移量(位置未知)方面不是固定的,但它们具有稳定的唯一标题 - 所以我想通过标题而不是偏移量来选择它们。

但问题是:库引发了关于重复标题的异常。有什么解决方案可以跳过它们并正确解析所有其他行吗?

或者在使用这个库之前如何从文件中删除它们的任何解决方法?这些重复的位置和数量事先是未知的。

谢谢!

4

1 回答 1

1

您可以自己映射列名。不要设置标题偏移量,这将使 League 返回带有整数键的行。

然后使用包含您想要的列名的数组来构建索引的映射。我做了一个小的工作示例:

测试.csv

name;;;age;;;;a;a;a;;;;
John;;;32;;;;;;;;;;
Jane;;;28;;;;;;;;;;

测试.php

//The columns you want to extract
$columns = ['name', 'age'];

$reader = Reader::createFromPath('test.csv', 'r+');
$reader->setDelimiter(';');
$grab = [];

//Find the indexes
foreach ($reader->fetchOne() as $index => $column) {
    if (in_array($column, $columns)) {
        $grab[$column] = $index;
    }
}

foreach ($reader->getRecords() as $i => $row) {
    if ($i == 0) {
        continue;
    }

    $filteredRow = [];
    foreach ($grab as $column => $index) {
        $filteredRow[$column] = $row[$index];
    }

    //$filteredRow now contains the needed columns
    var_dump($filteredRow);
}

输出:

array(2) {
  ["name"]=> string(4) "John"
  ["age"]=> string(2) "32"
}
array(2) {
  ["name"]=> string(4) "Jane"
  ["age"]=> string(2) "28"
}
于 2021-08-31T14:57:55.650 回答