steph steph - 13 days ago 6
PHP Question

Combine csv column values in PHP

I have a csv file with 5 rows :

id | price| name | sku | qty
1 | 22 | widget0 | abcd | 1
2 | 21 | widget1 | efgh | 1
3 | 10 | widget0 | abcd | 2
4 | 44 | widget1 | efgh | 1
5 | 22 | widget4 | mnop | 1



etc...
The first 3 columns are just here for visual purpose and are not used for what I need to achieve.
What I need to do is read the sku and qty data in the file and output the result.
I have to count the number of the same skus and get the total qty per sku.

Based on the example above, I need :

sku | qty
abcd | 3
efgh | 2
ijkl | 1
mnop | 1


With the following code, I can get the total number of the same skus in the file :

$file = ('my.csv');
$fh = fopen($file, 'rb');
$tag = array();
$qty = array();
$row=1;
while($col = fgetcsv($fh)) {
if($row == 1){ $row++; continue; } //skip 1st row
$num = count($fh);
if (isset($tag[$col[3]])) {
$tag[$col[3]]++;
}
else {
$tag[$col[3]] = 1;
}
}
print_r($tag);



It gives me :

sku | qty
abcd | 2
efgh | 2
ijkl | 1
mnop | 1





Which is not correct. I don't know how to get the qty column value and associate it to the total number of skus value in the csv file.

Any thoughts ?

Answer

Use below code for your solution

$file = ('my.csv');
$fh = fopen($file, 'rb');
$tag = array();
$qty = array();
$row=1;
while($col = fgetcsv($fh)) {
if($row == 1){ $row++; continue; } //skip 1st row
$num = count($fh);
if (isset($tag[$col[3]])) {
//$tag[$col[3]]++;
$tag[$col[3]] = (int)$tag[$col[3]] + (int)$col[4]; // where $col[4] = qty with forcing to `int` value
}
else {
$tag[$col[3]] = $col[4];
}
}
print_r($tag);

you need to make SUM of quantity instead just increase with +1

Hope this will help!