Dario
Dario

Reputation: 714

How to sum values from column 1 from csv and parse to csv PHP

I want to parse a csv file with multiple codes inside, some is repeating and i need to group it and keep a unic code at the end.

file.csv CSV file:

code    data
12345   45
12345   35
12346   2
12347   3
12345   5

file2.csv:

code,data
12345,85
12346,2
12347,3

PHP to Parse the CSV files:

<?php

$tsvFile = new SplFileObject('file.csv');
$tsvFile->setFlags(SplFileObject::READ_CSV);
$tsvFile->setCsvControl("\t");

$file = fopen('file2.csv', 'w');
$header = array('col1', 'col2');
fputcsv($file, $header, ',', '"');

foreach ($tsvFile as $line => $row) {
    if($line > 0) {
        fputcsv($file, array($row[0], $row[1]), ',', '"');
    }
}
fclose($file);

?>

This script is just parsing from tab to comma, but not grouping by code.

Any help is appreciated.

Upvotes: 0

Views: 1249

Answers (1)

Ignas
Ignas

Reputation: 1965

Try this:

$newData = array();
foreach ($tsvFile as $line => $row) {
    if ($line > 0) {
        if (isset($newData[$row[0]])) {
            $newData[$row[0]]+= $row[1];
        } else {
            $newData[$row[0]] = $row[1];
        }
    }
}
foreach ($newData as $key => $value) {
    fputcsv($file, array($key, $value), ',', '"');
}

Haven't tested this, but it should work.

Upvotes: 1

Related Questions