1
我有一個CSV檔案是這樣,names.csv:合併具有相同ID的行中.csv文件用PHP
"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);
}
有人可以幫我這個正確的解決方案,似乎很簡單,問題嗎? 提前謝謝!