使用php在.csv文件中合并具有相同id的行

时间:2012-03-08 02:11:45

标签: php csv merge rows

我有像这样的csv文件,names.csv:

"id","name"
"1","John"
"2","Joe"
"3","Peter"
"4","Frank"
"5","Bill"
...
"2","Steve"
"5","James"
"2","Mark"
"4","Anthony"

我想将“行”与相同的“id”合并,因此我得到以下结果:

"id","name"
"1","John"
"2","Joe , Steve , Mark"
"3","Peter"
"4","Frank , Anthony"
"5","Bill , James"

我想用php语言做这件事,但我没有得到解决方案。 通过我自己,我做了一些代码,但这对我的serverhost(循环中的循环)起了很多作用:

$myFile = "merged-names.csv";
$fh = fopen($myFile, 'w') or die("can't open file");

if (($handle = fopen("names.csv", "r")) !== FALSE) 
{
  $line = fgets($handle);
  $val = explode(",", $line);
  $max = (count($val))/2;

  for ($i=0; $i <= $max; $i+2)
  {
    $id = $val[$i];
    $name = $val[$i+1];
    $stringData = "\"".$id."\"".",";
    fwrite($fh, $stringData);
    $stringData = "\"".$name."\"";
    fwrite($fh, $stringData);

    for ($e=0; $e <= $max; $e+2)
    {
  if (strcmp($id, $val[$e]) == 0)
  {
        if($i != $e)
    {
      $stringData = "\"".$val[$e+1]."\"";
      fwrite($fh, $stringData);
        }
  }
    }

    $stringData = "<br>";
    fwrite($fh, $stringData);

  }
fclose($handle);
 }

有人可以帮我找到合适的解决方案吗,看起来很简单,有问题吗? 提前谢谢!

2 个答案:

答案 0 :(得分:2)

这就是我要做的事情:

$lines = file('merged-names.csv');

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

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

答案 1 :(得分:0)

这个怎么样......

$temp = array();
if (($handle = fopen("names.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $name = $data[1];
        $id = $data[0];
        if (!isset($temp[$id]))
            $temp[$id] = array();
        $temp[$id][$name] = 1;
    }
    fclose($handle);
}
foreach ($temp as $k => $v) {
    echo $k.","."\"".implode(",", array_keys($v))."\""."\n";
}