dongzhuo3059 2015-03-23 14:26
浏览 35
已采纳

使用php汇总csv文件中的行数据

I am trying to sum a single row of data(numbers) from a csv file to display the total number using php. this is the csv file I have:

A

0.01
0.1
0.02
0.01
0.02
0.01
0.02

Basically it stretches on. A is basically the first row alphabet in excel.

Basically it stretches on. I am trying to sum up the row in PHP.

This is my code so far:

if (($handle = fopen("file.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
   $data = array();

   echo array_sum($data);
  }
}

My output is basically : 000000000000000000000000000000000000000000000000000

I cant seem to figure out why? Could anyone assist me with this?

  • 写回答

1条回答 默认 最新

  • dragonsun00000 2015-03-23 14:45
    关注

    You could try like this

    <?php
    $file = fopen("file.csv","r");
    $sum = 0;
    while(!feof($file)) {
        $csv = fgetcsv($file,1024);
        if(!$csv[0]){
                print $sum."
    ";
        }
        $sum = $sum + $csv[0];
    }
    

    or declare array before the while loop

    <?php
    $file = fopen("file.csv","r");
    $sum = array();
    while(!feof($file)) {
        $csv = fgetcsv($file,1024);
        array_push($sum,$csv[0]);
    }
    echo array_sum($sum)."
    ";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题