0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.