1

我有一件有趣的工作要完成

我有很多已转换为 CSV 的电子表格 - 这些电子表格最初是作为具有一定数量列的模板。

不幸的是,随着时间的推移,人们添加了列并删除了它们。

有没有办法可以调整以下代码以从每个 CSV 中选择某些列名

foreach($fileinfos as $pathname => $fileinfo) {
    if (!$fileinfo->isFile()) continue;
      if(substr($pathname,-3) == 'csv'){

            $file = fopen($pathname, "r"); 
            while ($line = fgetcsv($file,0,'^','¬')){
               echo substr($pathname,56) .'   '.$numcols.'<br>';          
             }
            fclose($file);
      }
}

更新:

这是我接受的列数组

Array
(
    [0] => Date Raised
    [1] => QA phase
    [2] => Item ID
    [3] => Screen Number
    [4] => Reason
    [5] => Matches originals?
    [6] => Issue / Comments
    [7] => Raise with Client?
    [8] => Raised By
    [9] => Status
    [10] => TP/AS Status Initials
    [11] => TP/AS Status  date
    [12] => TP/AS Status Comment
    [13] => Retested by
    [14] => Retested date
    [15] => Retested Comment
)

这是我的可用数组

Array
(
    [0] => Date Raised
    [1] => QA phase
    [2] => Item ID
    [3] => Screen Number
    [4] => exam 
    [5] => Reason
    [6] => Matches originals?
    [7] => Issue / Comments
    [8] => Raise with Client?
    [9] => Raised By
    [10] => Status
    [11] => TP/AS Status Initials
    [12] => TP/AS Status  date
    [13] => TP/AS Status Comment
    [14] => dd Comments
    [15] => PM Comments
    [16] => Retested by
    [17] => Retested date
    [18] => Retested Comment
)

数组结合 dosnt 工作。

4

2 回答 2

3
$file = fopen($pathname, 'r');
$headers = fgetcsv($file, 0, '^', '¬');

while ($line = fgetcsv($file, 0, '^', '¬')) {
    $line = array_combine($headers, $line);

    var_dump($line);
    // access specific fields using $line['columnName']
}
于 2012-12-07T14:29:31.817 回答
2

我会尝试这样的事情:

$csv = array();
$columnnames = fgetcsv($fp, 1024);
while (true == ($columns = fgetcsv($fp, 1024))) {
    $row = array_combine($columnnames, $columns);
    $csv[] = $row;
}

在这样的 CSV 文件上

id,name,email
1,benjamin,benjamin@example.com
2,rob,rob@example.com

$csv变量应包含如下内容:

1 => array(
    'id' => 1,
    'name' => 'benjamin',
    'email' => 'benjamin@example.com'
)
...
于 2012-12-07T14:31:36.730 回答