[英]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-對其進行強制轉換:
<?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>";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.