dongwenxiu5200 2016-10-17 06:00
浏览 20
已采纳

在PHP中组合csv列值

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 ?

  • 写回答

2条回答 默认 最新

  • drgovyk64676 2016-10-17 06:12
    关注

    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!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程