2016-10-17 67 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