dtkvlj5386 2017-02-23 11:42
浏览 21
已采纳

如何获取特定Array索引值的总和

I am reading data from file and displaying array like below code :

  if (($fp = fopen("test.txt", "r")) !== FALSE) {       
    $count = 0;
    while(($row = fgetcsv($fp)) !== FALSE)
    {


        $row = explode("|",$row[0]);
        foreach($row as &$el)
        {
            $el=trim($el);

        }
        $count++;
                $tot = array_sum(array_column($row,2));
        echo "<pre>";print_r($row); 
                if($count>3)
        {
            break;  
        }
      echo "Coumt :".$tot;  
    }

          echo "Coumt :".$tot;
    fclose($fp);
}

Test.txt file data :

005-4410040             |BIRM|      0 
005-4410040             |CHI |  
450 005-4410040         |CIN |    144

I want total sum of 2nd index of the array it means 320 + 450 + 144 in seperate varriable.

How can i achieve this ? Already tried array_column but its not working.

Update What i have tried :

$sum = array_sum(array_column($row,$row['2']));
  • 写回答

2条回答 默认 最新

  • doulongsha5478 2017-02-23 11:46
    关注

    You should be able to achieve that using array_column() and array_sum() like this

    $row = [
            ['005-4410040','BIRM',1],
            ['005-4410040','CHI',2],
            ['005-4410040','CIN',3]
        ];
    
    $tot = array_sum(array_column($row, 2));
    

    RESULT

    6
    

    After code added to the question:

    You are not understanding fgetcsv() correctly, it gets one line at a time. So each call to fgetcsv return one line from the file which you explode into $row

    All you need to do is accumulate $row[2] as you process over the lines of the file.

    if (($fp = fopen("test.txt", "r")) !== FALSE) {       
        $count = 0;
        $tot = 0;
    
        while(($row = fgetcsv($fp)) !== FALSE)
        {
            $row = explode("|",$row[0]);
            $count++;
            // I see one line with no value so to be safe
            $tot += $row[2] != '' ? $row[2] : 0;
    
            if($count>3) {
                break;  
            }
            echo "Coumt : $tot";  
        }
    
        echo "Coumt : $tot";
        fclose($fp);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA