Group all lines with the same word in first column in csv

361 Views Asked by At

I have two columns in my csv file: first_column and second_column. I would like to group all the rows in second column into one string separated by "," if they all have the same word in the first column then output them into a text file.

first_column   second_column
a              Chris
a              Jake
a              Paula
b              Anita
b              Lionel
b              Sheila

Desired output

a: Chris, Jake, Paula
b: Anita, Lionel, Sheila

This is what I tried. I seem to be only getting the first letter from the second_column. Any pointers would be great.

$csv_file = fopen("test.csv", "r");
$text_file = fopen("test.txt","w");

$data = array();

if ($csv_file) 
{
    while (($line = fgets($csv_file)) !== false) 
    {
        $column_1 = $line[0];
        $column_2 = $line[1];

        if (!empty($column_1)) 
        {
            $data [$column_1] = column_2;
        }
    }

    fclose($csv_file);
    fclose($text_file);
} 

else 
{
    // error opening the file.
}

//print_r($data);
2

There are 2 best solutions below

0
On BEST ANSWER

This should work for you:

Here I first get your .csv file into an array with file(). Then I loop through each line and create an array, where the first column is the key and the second column a value of the sub array.

After this you can loop through your created array and implode() each sub array with the key to the expected line which you want. Then you can just save the data with file_put_contents() into your .txt file.

<?php

    $csv_file = "test.csv";
    $text_file = "test.txt";

    $lines = file($csv_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    array_shift($lines);
    foreach($lines as $line) {
        list($key, $value) = explode(",", $line);  //Change your .csv delimiter here, if you use something else than ,
        $data[$key][] = $value;
    }

    foreach($data as $key => $arr)
        $content[] = $key . ": " . implode(",", $arr) . PHP_EOL;

    file_put_contents($text_file, $content);

?>
0
On

Storing result in an data array and then wring it bacj to text file should work.

$csv_file = fopen("test.csv", "r");
$text_file = fopen("test.txt","w");

$data = array();

if ($csv_file) 
{
  while (($line = fgets($csv_file)) !== false) 
  {
     $column_1 = $line[0];
     $column_2 = $line[1];

     if (!isset($data[$column_1])) 
     {
        $data[$column_1] = column_2
     } else {
        $data[$column_1] = $data[$column_1] .',' . $column_2
     }
  }

   foreach($data as $k=>$d ){
      fputs($text_file, "$k: $d") ;
  }

   fclose($csv_file);
   fclose($text_file);
} 
else 
{
  // error opening the file.
}