PHP - 从多个文件中添加数字

时间:2012-10-07 20:17:12

标签: php addition

我一直遇到PHP问题 - 我非常新的。大多数情况下使用来自其他来源的代码片段来做我想要的事情。

无论如何,这是情况。假设我在单独的目录中有4个单独的文本文件。每个文本文件只包含一个数字。我可以在PHP中做什么,将所有这些数字一起添加(+),并将输出写入另一个.txt文件?

原始4个文本文档中的数字会定期更新(每2-8秒),因此如果需要指定添加脚本经常更新,那将非常棒。

谢谢, - Kovacic

3 个答案:

答案 0 :(得分:1)

$sum = 0;
foreach (array('/path1/1.txt', '/path2/2.txt', '/path3/3.txt', '/path4/4.txt') as $f)
    $sum += intval(trim(file_get_contents($f)));

echo $sum, PHP_EOL;

答案 1 :(得分:0)

你可以做一个

$filename = 'abs/path/to/first/file';
$fh = fopen($filename,'r');
$firstNumber = fread($fh,filesize($filename));
fclose($fh);

并重复所有4个文件

$sum = $firstNumber+$second+$third+$fourth;
$filename = 'abs/path/tofile';
$fh = fopen('abs/path/tofile','w');
fwrite($fh,$sum);
fclose($fh);

最后将所有代码放在无限循环中

while(true){
    // do some code to calculate some or function call
    sleep(5);
}

答案 2 :(得分:0)

要将四个文件中的数字相加并将它们写入新文件,您可以使用

file_put_contents(
    '/path/to/sum.txt',
    array_sum(
        array_merge(
            file('/path/to/a/file.txt'),
            file('/path/to/b/file.txt'),
            file('/path/to/c/file.txt'),
            file('/path/to/d/file.txt')
        )
    )
);

不确定是什么意思“如果需要指定添加脚本经常更新会很棒。”