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!