[英]How to concatenate values from multiple rows with the same id to a comma separated with unique id
I have a CSV file, name it data.csv
, that looks like this: 我有一个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
What I need is to concatenate the values in the field data
in a single one for all the rows with the same id
. 我需要将具有相同id
所有行的字段data
中的值合并为一个。 Then, print those newly obtained rows in another CSV file. 然后,将这些新获得的行打印在另一个CSV文件中。
I managed to arrange the values in an array, but at the conversion to the CSV file it saves only one of them. 我设法将值排列在一个数组中,但是在转换为CSV文件时,它仅保存其中一个。
Here is my code 这是我的代码
$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);
At the end, the resulting CSV file should look like this: 最后,生成的CSV文件应如下所示:
id,data
"1","Data text, Data text 1, Data text 2"
"2","Data text x, Data text y"
Well, I think you could do what you ask in an easier way. 好吧,我认为您可以以更简单的方式完成您的要求。
I just used fgetcsv()
and fputcsv()
functions to handle the extraction and insertion of a well formed and well formatted row from/to file. 我只是使用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);
}
Here's the input I used to test the script: 这是我用来测试脚本的输入:
id,position,data
1,1,first string
1,2,second string
1,3,third string
2,1,fourth string
2,2,fifth string
And here's the output file i obtained: 这是我获得的输出文件:
id,data
1,"first string second string third string"
2,"fourth string fifth string"
As you can see, the data
part of the rows is now quoted. 如您所见,行的data
部分现在被引用了。 That's just the way standard CSV handles strings. 这就是标准CSV处理字符串的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.