如何使用fgetcsv从CSV获取特定列?

时间:2012-12-07 14:03:04

标签: php fgetcsv

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

我有很多电子表格,我已将其转换为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工作。

2 个答案:

答案 0 :(得分: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']
}

答案 1 :(得分: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'
)
...