2016-10-17 62 views
0

CSV列的值我有5行的CSV文件:结合在PHP

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 


等等 前3列是这里只是为了视觉目的,而不是用来做什么,我需要实现。 我需要做的是读取文件中的sku和qty数据并输出结果。 我必须计算相同skus的数量并获得每sku的总数量。

基于上面的例子中,我需要:

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

用下面的代码,我可以得到的文件相同的SKU总数:

$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); 


它给我:

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



这是不正确的。我不知道如何获得qty列值并将其与csv文件中skus值的总数相关联。
有什么想法?

回答

0

使用您的解决方案

$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); 

您需要的数量,而不是SUM只是+1

希望这将有助于增加!

+0

Awsome阿尔伯特,作品像一个魅力! – steph

+0

WC。请upvote答案并接受它,所以它会用于其他用户将有同样的事情。 :) –

0

尝试此解决方案下面的代码

$file = ('my.csv'); 
$fh = fopen($file, 'rb'); 
$tag = array(); 
$qty = array(); 
$row=1; 

//skip first row 
fgetcsv($fh, 10000, ","); 

while($col = fgetcsv($fh,10000)) { 

$num = count($fh); 
if (isset($tag[$col[3]])) { 
$tag[$col[3]]++; 
} 
else { 
$tag[$col[3]] = 1; 
} 
} 
print_r($tag); 
+0

嗨,谢谢,但这并没有改变任何东西... – steph