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


sum of array values in php using array

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

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

为了确保PHP将$data视为int-cast it:

 <?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:您需要使用新行作为分隔符,而不是逗号:)编辑了我的示例,新的最佳方法是使用文件()

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