简体   繁体   English

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

[英]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.

相关问题 如何显示多行逗号分隔值从MySQL数据库 - How to display multiple rows of comma separated values from mysql db 在包含多个ID(用逗号分隔)的列中选择以ID搜索的行 - Select rows searching with an id in a column that contains multiple ids separated by a comma 获取从表中传递多个分隔的逗号ID的记录,其中ID在mysql表中也以逗号分隔 - get records with passing multiple separated comma id from table where id is also comma separated in mysql table 如何从一个表扩展以逗号分隔的字段并将其复制到使用相同唯一ID的第二个表的多个字段中 - How to expand a comma delimited field from one table and copy it into multiple fields in a second table which uses the same unique id 如何将一个id与多个逗号分隔的ID匹配 - how to match one id with multiple comma separated ids 如何在Codeigniter中从每个ID中以逗号分隔的其他表中选择多个数据 - How to select multiple data from other table from each id separated by comma in codeigniter 如何在数据库中具有相同ID的多行中插入复选框的多个值 - How to insert multiple values of checkbox in multiple rows with same id in database 从db到array复选id_value复选框,从数组中选择Insert multiple values复选框到以逗号分隔的一列 - Select id_value from db into array checkbox and Insert multiple values from array checkbox to one column with comma separated 如何从数据库中选择具有相同id值的多行值并以ajax显示? - How to pick multiple rows of values of the same id value from the database and display in ajax? SQL如何从多行逗号分隔列表中删除数字 - SQL how to remove a number from comma separated list, on multiple rows
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM