0

我有一个包含两列“id”和“name”的 csv,我想合并共享相同 id 的行并用逗号分隔它们。

id      name
39695   NFL: Cowboys @ Giants
39699   NFL: Colts @ Bears
39699   NFL: Steelers @ Broncos
39699   NFL: Eagles @ Browns
39699   NFL: Panthers @ Buccaneers

进入

id      name
39695   NFL: Cowboys @ Giants
39699   NFL: Colts @ Bears, NFL: Steelers @ Broncos, NFL: Eagles @ Browns, NFL: Panthers @ Buccaneers

我所需要的只是一个回显或一个新的 .csv 文件。

感谢您的帮助。

**编辑

<"?php

$lines = file('sport3.csv');

foreach($lines as $line)
{
list($id, $name) = explode(',', $line);
$merged[$id][] = $name;
}

foreach($merged as $id => $vals)
{
echo '"' . $id . '", "' . implode(',', $vals) . '\"\n';
}
?>
4

1 回答 1

1

在 PHP 中使用专为 CSV 函数设计的更安全:

// parse thru data
$mergedData = array();
$handle = fopen('sport3.csv', 'r');
if (!$handle) throw new Exception("Can't open original CSV file");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    list($id, $name) = $data;
    if (empty($mergedData[$id])) $mergedData[$id] = array();
    $mergedData[$id][] = $name;
}
fclose($handle);

// save merged data
if (count($mergedData) > 0) {
    $handle = fopen('sport3-merged.csv', 'w');
    if (!$handle) throw new Exception("Can't open CSV file for merged data");
    foreach($mergedData as $id => $vals) {
        array_unshift($vals, $id);
        if (!fputcsv($handle, $vals)) throw new Exception("Can't write data to merged CSV file");
    }
    fclose($handle);
}

希望有帮助。

于 2013-03-19T04:08:08.890 回答