0

大家好,我立即道歉,因为我在网站上看到了各种线程,但不幸的是我的知识仍然不足以完成我的项目。我有一个文本文件,我必须对每列求和(只需要总计):

1003|name1|1208.00|2.00  |96.00  |0.00|0.00|0.00|0.00|98.00  |90.95  |7.05  |8516.40
1011|name2|1450.00|2.00  |49.00  |0.00|0.00|0.00|0.00|51.00  |44.62  |6.38  |9243.7
1004|name3|1450.00|25.00|170.00|0.00|0.00|0.00|0.00|195.00|175.75|19.25|27912.5 <br>
1002|name4|765.00 &nbsp;|1.00&nbsp;&nbsp;|17.00&nbsp; |0.00|0.00|0.00|0.00|18.00&nbsp; |15.13&nbsp; |2.87&nbsp; |2193.26

我需要得到这个(我在 linux 上有这个文件,然后我们可以使用 Bash、PHP、Mysql...):

1003|name1|1208.00|2.00&nbsp;&nbsp;|96.00&nbsp; |0.00|0.00|0.00|0.00|98.00&nbsp; |90.95&nbsp; |7.05&nbsp; |8516.40
1011|name2|1450.00|2.00&nbsp;&nbsp;|49.00&nbsp; |0.00|0.00|0.00|0.00|51.00&nbsp; |44.62&nbsp; |6.38&nbsp; |9243.7
1004|name3|1450.00|25.00|170.00|0.00|0.00|0.00|0.00|195.00|175.75|19.25|27912.5 <br>
1002|name4|765.00 &nbsp;|1.00&nbsp;&nbsp;|17.00&nbsp; |0.00|0.00|0.00|0.00|18.00&nbsp; |15.13&nbsp; |2.87&nbsp; |2193.26 <br>
xxxx|Total&nbsp; |4873.00|30.00|332.00|0.00|0.00|0.00|0.00|362.00 |326.45|35.55|47865.86

其中 xxxx 是 ID 号(此处没有总和)。

我一直在尝试在 PHP 和 MySQL 中做到这一点——到目前为止还没有运气。

4

4 回答 4

0

伪代码:

open source file for reading
open destination file for writing
initialise totaling array to zero values
while not EOF
  read in line from file
  explode line into working array
  for x=2 ; x<14; x++ 
    add totalling array with floatval( working array )
    write line out to destination file
close read file
write out totals array to destination file
close destingation file
于 2013-09-10T11:27:58.120 回答
0

尝试将文本文件数据放入 Excel 电子表格,然后将列相加。

您可以使用 VB 将文本导入 excel,然后继续将每列的值相加。

于 2013-09-10T11:28:00.280 回答
0

1) 全部替换 | chars with , using str_replace 2) 使用 str_getcsv 从上述生成的 csv 字符串中创建数组 3) 使用 foreach 并遍历每一行并计算总数

一些PHP代码

$str = file_get_contents('myfile.txt');
$str = str_replace('|', ',', $str);
$csv = str_getcsv($str);
$totals = array(0,0,0,0);
foreach ($csv as $row) {
    $totals[0] += trim($row[0]);
    $totals[1] += trim($row[2]);
    $totals[2] += trim($row[3]);
    $totals[3] += trim($row[4]);
}

$totals 数组包含所有总数!

于 2013-09-10T11:28:33.087 回答
0

尝试类似:

$file = '/path/to/your_file.txt';
if ( ($file = fopen($file, "r")) !== FALSE) {
    $total = 0;
    $row_1 = 0;
    while (($line = fgetcsv($file, 1000, "|")) !== FALSE) {

        // brutal dirt sanitization
        foreach ( $line as $k => $v ) {
           $line[$k] = (float) preg_replace('#[^0-9\.]#','', $v);
        }

        $total = $total + array_sum(array_slice($line, 2));
        $row_1 = $row_1 + array_sum(array_slice($line, 2, 1));
        //...
    }
    echo $total.' | '.$row_1; //...
}
else echo 'error ...';

此外,您可以通过使用回调函数将 array_sum() 替换为 array_map() 来清理每一行

于 2013-09-10T11:29:33.170 回答