如何将具有相同id的多行的值连接到用唯一id分隔的逗号

时间:2014-09-01 17:54:06

标签: php file csv

我有一个CSV文件,名称为data.csv,如下所示:

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

我需要的是将data字段中的值连接到一个具有相同id的所有行中的值。然后,将这些新获得的行打印在另一个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"

1 个答案:

答案 0 :(得分: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处理字符串的方式。