需要帮助,我有2个csv文件
january.csv
包含3列:
02Jan2020 Marilyn 31570.29
02Jan2020 Nancy 30000.00
06Jan2020 John 1570.29
06Jan2020 Nancy 5000.00
10Jan2020 Marilyn 570.29
10Jan2020 Nancy 10000.00
.... etc
suppliers.csv
Marilyn
John
Nancy
..etc
现在,我想对与january.csv
匹配的金额(suppliers.csv
)中的所有值进行求和
Nancy 30000.00
Nancy 5000.00
Nancy 10000.00
echo sum 45000.00
经过研究后,我才开始,但不确定比较是否正确以及如何对返回值求和
$filename="january.csv";
$base="suppliers.csv";
$NOWcodes = array();
$file = fopen($base, 'r'); //registred opened
while (($line = fgetcsv($file)) !== FALSE) { array_push($NOWcodes, $line[0]); }
fclose($file);
$file = fopen($filename, 'r'); //all nomes
while (($line = fgetcsv($file)) !== FALSE) {
if(!in_array($line[0],$NOWcodes)){ } //Not sure how to do it here
echo array_sum($sum)."\n";
fclose($file);
答案 0 :(得分:0)
CSV文件中的数据仅由一个分隔符分隔。显示的数据必须采用这种格式,以便可以正确读取。我在january.csv中使用了一个空格。
供应商存储在一个数组中。
$filename = "january.csv";
$base = "suppliers.csv";
$suppliers = [];
$file = fopen($base, 'r');
while (($line = fgetcsv($file)) !== FALSE) {
$suppliers[] = $line[0];
}
fclose($file);
然后可以在另一个for循环中检查供应商并进行分组/汇总。
$file = fopen($filename, 'r');
$sum = [];
while (($row = fgetcsv($file,0," ")) !== FALSE) {
$name = $row[1];
if(in_array($name,$suppliers)){
if(!array_key_exists($name,$sum)) $sum[$name] = 0.0;
$sum[$name] += $row[2];
}
}
fclose($file);
//Output Result
var_export($sum);
结果:
array (
'Marilyn' => 32140.58,
'Nancy' => 45000.0,
'John' => 1570.29,
)
array_sum()可用于所有供应商的总数:
$total = array_sum($groups);