如何将具有相同ID的多个行中的值连接到用唯一ID分隔的逗号 [英] How to concatenate values from multiple rows with the same id to a comma separated with unique id

查看:340
本文介绍了如何将具有相同ID的多个行中的值连接到用唯一ID分隔的逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a CSV file, name it data.csv, that looks like this:

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文件中。

What I need is to concatenate the values in the field data in a single one for all the rows with the same id. 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.

以下是我的代码

$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文件应如下所示:

At the end, the resulting CSV file should look like this:

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


推荐答案

我刚刚使用 fgetcsv() fputcsv()函数,用于处理从/到文件的格式良好和格式良好的行的提取和插入。

I just used fgetcsv() and fputcsv() functions to handle the extraction and insertion of a well formed and well formatted row from/to file.

$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"

c $ c> data 部分行现在被引用。这只是标准CSV处理字符串的方式。

As you can see, the data part of the rows is now quoted. That's just the way standard CSV handles strings.

这篇关于如何将具有相同ID的多个行中的值连接到用唯一ID分隔的逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆