使用数组的php中数组值的总和

时间:2015-03-23 11:38:26

标签: php arrays loops

我正在学习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

1 个答案:

答案 0 :(得分: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:您需要使用新行作为分隔符,而不是逗号:)编辑我的样本 - 新的最佳方法是使用{{3 }}

$data= file('https://www.mywebsite.com/test.csv');
$total = 0;

foreach($data as $current) {
    $total += $current;
}

echo "  $total<br>";