Link to home
Start Free TrialLog in
Avatar of danialbb
danialbb

asked on

CSv Unique column A data while adding up column b data

I have to 2 columns of information in a CSV file example

Column A       Column B (stats)

pink                      2
pink                      3
red                       1
red                       6
red                       3
black                    1
black                    5
black                    2

the results I am after are Column A. unique words only but at the same time to add up the stats with matching keyword stats

The results should be

pink                5    
red                 10
black              8

If it could be written as another CSV file it would be appeciated
Avatar of lavinpj1
lavinpj1

Hello,

Can you post an example of the CSV format you're working with? I assume it's something like:

pink,2
pink,3
red,1
red,6

but clarification would be handy.

Phil
Avatar of danialbb

ASKER

Yes thats the format

Column A , column B

pink,1
pink,3

etc
<?php
$filename = '/home/phil/file.csv';

// Read the file
$handle = fopen($filename, 'r');
$contents = trim(fread($handle, filesize($filename)));

// Array for output
$output = array();

// Split by \n and loop
$lines = explode("\n", $contents);

foreach ($lines as $line) {
      // Split by , and enumerate
      $line = rtrim($line);
      $temp = explode(',', $line);

      $output[$temp[0]] += $temp[1];
}

// Loop and output
foreach ($output as $key=>$val) {
      echo "{$key},{$val}\n";
}
?>

That reads from a file and outputs it to the page/console. Let me know if you had other intentions for input/output.

Phil
Could you write to a csv file please. And I will accept the answer once tested.

Thanks for this.
ASKER CERTIFIED SOLUTION
Avatar of lavinpj1
lavinpj1

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Excellent work Thanks Again