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 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题