lundi 2 juin 2014

Convert csv in php and get unique value


Vote count:

0




I would like to convert a csv file that has duplicate contents and i would like to sum the quantity and extract the price without sum it.


file.csv :



code,qty,price
001,2,199
001,1,199
002,2,159
002,2,159


Actual php that sum the quantiy and get a result with unique value and total qty.



<?php
$tsvFile = new SplFileObject('file.csv');
$tsvFile->setFlags(SplFileObject::READ_CSV);
$tsvFile->setCsvControl("\t");
$file = fopen('file.csv', 'w');
$header = array('sku', 'qty');
fputcsv($file, $header, ',', '"');

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), ',', '"');
}
fclose($file);

?>


the result for this is:



code,qty
001,3
002,4


and i would like to add price, but without sum it.



asked 40 secs ago






Aucun commentaire:

Enregistrer un commentaire