2012-12-07 46 views
1

我有一件有趣的工作要完成如何使用fgetcsv从CSV中获取特定列?

我有很多电子表格,我已经转换为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); 
     } 
} 

UPDATE选择特定的列名:

这是我接受的列

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工作。

+3

是有第一条线确定th e列名?您可以阅读第一行并记住列名,以在后面的所有行上创建一个数组,列名将用作此数组中的键 –

+0

第一行包含列名称 - 那么您是说解析第一行然后从那里建立一个数组,并使用键跳过某些列? – Rob

回答

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'] 
} 
+0

只有在中间没有添加列的情况下,此功能才有效 – Rob

+0

您是什么意思?这个解决方案的具体问题是什么? – deceze

+1

@Rob我认为你必须拆分你的csv文件,并为所有可用的模式创建单个文件。在中间添加一列是销毁它们之后的行的模式。或者您必须在模式更改点重新读取列名称。 –

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,[email protected] 
2,rob,[email protected] 

$csv变量应该是这样的:

1 => array(
    'id' => 1, 
    'name' => 'benjamin', 
    'email' => '[email protected]' 
) 
... 
相关问题