dongrong7267 2012-03-08 02:11
浏览 63
已采纳

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

I have a csv-files like this, names.csv:

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

I want to merge the "rows" with the same "id" so I reach the following result:

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

I want to do this with php language, but I don't get a solution. By my self I made some code, but that makes to much work for my serverhost (loops in loops):

$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);
 }

Can someone help me with the right solution for this, seems so simply, problem? Thank you in advance!

  • 写回答

2条回答 默认 最新

  • dsrw29618 2012-03-08 02:26
    关注

    how about this...

    $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))."\""."
    ";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应