【问题标题】:sum of array values in php using arrayphp中使用数组的数组值的总和
【发布时间】:2015-03-23 20:41:44
【问题描述】:

我正在学习 php 作为我学习的一部分,目前我想将一个 csv 文件读入一个数组,然后计算所有值。我已成功读取文件并可以显示 csv 文件中的所有值,但无法对它们求和/相加以求得总数。

到目前为止,这是我的代码:

   <?php
            $data= explode(",",
              file_get_contents('https://www.mywebsite.com/test.csv')
            );
    $total = 0;
            $lengthofarray=count($data);

            for($x=0;$x<=$lengthofarray;$x++)
            {
                $total = $total + $x; 
//I am not sure if I am missing something here in order to make it working
            }
            echo "  ".$total."<br/>";
    ?>

我知道这是一个基本问题,但我花了 12 多个小时才找到解决方案,并在互联网上搜索以找到解决方案,但无法做到。

以下是我的 csv 文件中的值:

0.78
0.19
0.78
0.98
0.65
0.79
0.34
0.29
0.55
0.95

【问题讨论】:

    标签: php arrays loops


    【解决方案1】:

    你使用了 $x(迭代器)而不是你从文件中得到的 $data :)

    为了确保 PHP 将 $data 视为 int - 强制转换:

     <?php
        $data= explode("\n",file_get_contents('https://www.mywebsite.com/test.csv'));
        $total = 0;
        $lengthofarray=count($data);
    
        for($x=0;$x<=$lengthofarray;$x++) {
           $total = $total + (int)$data[$x];
        }
        echo "  ".$total."<br/>";
     ?>
    

    但更好的方法是使用 foreach:

    $data= explode("\n",file_get_contents('https://www.mywebsite.com/test.csv'));
    $total = 0;
    
    foreach($data as $current) {
        $total += $current;
    }
    echo "  ".$total."<br/>";
    

    要加载 .csv 文件,有 fgetcsv():

    $data = fgetcsv(fopen('test.csv','r'));
    

    更新:现在您发布了 .csv:您需要使用新行作为分隔符,而不是逗号 :) 编辑了我的示例 - 新的最佳方法是使用 file()

    $data= file('https://www.mywebsite.com/test.csv');
    $total = 0;
    
    foreach($data as $current) {
        $total += $current;
    }
    
    echo "  $total<br>";
    

    【讨论】:

    • 嗨 Marc 感谢您的建议,但是当我使用您的代码时 $data= explode(",",file_get_contents('mywebsite.com/test.csv')); $总计 = 0; foreach($data as $current) { $total += $current; } echo " ".$total."
      ";它只给我数组中第一个位置的值。我也不确定 fgetcsv(...) 是否应该替换代码中的第一行?如果是,那么我在运行代码时会收到错误消息
    • 您可以发布您的 .csv 文件吗?确保在使用 fgetcsv 时打开文件处理程序(并使用相对路径)
    • 是的,我已经设法解决了这个错误,但是我的循环只运行了一次,并给了我 array[0] 的值,就是这样。我有一个只有一列和超过 2000 行的 csv,我想在 csv 文件中添加所有行。
    • 你能发布你当前的代码和.csv吗? (至少 10 个条目,以便我查看我的代码是否有问题)
    • 这是我正在使用的代码: $data= fgetcsv(fopen('mywebsite.com/test.csv')); $总计 = 0; foreach($data as $current) { $total += $current; } echo " ".$total."
      ";对于 CSV 文件,我不确定如何在此处上传,因为没有上传文件的选项...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多