2014-09-01 117 views
1

逗号隔开我有一个CSV文件,将其命名为data.csv,看起来像这样:如何用相同的ID串联多行值与唯一的ID

id,position,data 
1,1,Data text 
1,2,Data text 2 
1,3,Data text 3 
2,1,Data text x 
2,2,Data text y 

我需要的是来串联对于所有具有相同id的行,单个行中的值为data。然后,将这些新获取的行打印到另一个CSV文件中。

我设法将值排列在一个数组中,但在转换为CSV文件时,它只保存其中的一个。

这里是我的代码

$file = 'data.csv'; 
$tsvFile = new SplFileObject($file); 
$tsvFile->setFlags(SplFileObject::READ_CSV); 
$tsvFile->setCsvControl(","); 

foreach ($tsvFile as $line => $row) { 
    if ($line > 0) { 
      $newData[$row[0]] = array('id'=>$row[0], 'position'=>$row[1], 'data'=>$row[2]); 
      $newData[$row[1]] = $row[2]; 
    } 
} 
// 
echo '<pre>'; 
var_dump($newData); 
// 
$fp = fopen('data2.csv', 'w'); 
foreach ($newData as $fields) { 
    fputcsv($fp, $fields); 
} 
fclose($fp); 

最后,所产生的CSV文件应该是这样的:

id,data 
"1","Data text, Data text 1, Data text 2" 
"2","Data text x, Data text y" 
+0

为了直观:您有一个CSV('data.csv'),看起来像第一个突出显示的块,并且想要将它解析为另一个看起来像最后一个突出显示的块的CSV文件? – Overflowh 2014-09-01 18:52:35

+0

。 Thx ... – Dario 2014-09-01 19:08:42

回答

0

好吧,我想你可以做你在一个更简单的方法问什么。

我刚刚使用了fgetcsv()fputcsv()函数来处理从文件中提取和插入格式良好的行。

$output = array(); 

if ($in_handle = fopen('data.csv', 'r')) { 
    // discard the first line, the one with the names of the fields 
    $input = fgetcsv($in_handle); 

    // get an array out of a row from the file data.csv 
    while ($input = fgetcsv($in_handle)) { 
     // create an array with only the needed fields 
     $current_row = array(
      'id' => $input[0], 
      'data' => $input[2] 
     ); 

     if (array_key_exists($current_row['id'], $output)) { 
      $output[$current_row['id']]['data'] .= ' ' . $current_row['data']; 
     } else { 
      $output[$current_row['id']] = $current_row; 
     } 
    } 

    fclose($in_handle); 

    if ($out_handle = fopen('new_file.csv', 'w')) { 
     // recreate the first line of the file deleted before 
     $fields_names = array('id', 'data'); 
     fputcsv($out_handle, $fields_names); 

     // begins at 1 because there isn't any value before 
     for ($i = 1; $i <= count($output); ++$i) 
      fputcsv($out_handle, $output[$i]); 
    } 

    fclose($out_handle); 
} 

这是我用来测试脚本的输入:

id,position,data 
1,1,first string 
1,2,second string 
1,3,third string 
2,1,fourth string 
2,2,fifth string 

,这里是我得到的输出文件:

id,data 
1,"first string second string third string" 
2,"fourth string fifth string" 

正如你所看到的,行的data部分现在引用。这只是标准的CSV处理字符串的方式。

+0

确实!,thx很多! – Dario 2014-09-02 08:00:45

+0

它返回警告:fputcsv()期望参数2是数组,null在 – Dario 2014-09-02 17:20:31

+0

中给出它__is__是一个数组。只要检查你的文件和'for'计数器。正如循环上方的注释中所述,我从'1'开始创建'$ i',因为之前没有索引。现在,您必须将其适应您的代码。 – Overflowh 2014-09-02 18:09:08