来自文件的PHP总和 [英] PHP Sum from a file
问题描述
我在这里仍在学习使用PHP进行编码,此刻我已经遇到了一个问题.
I'm here still learning to code with PHP, and I've got into one question at the moment.
我有一个.txt文件,说"results.txt",其中包含5个不同的选项,后面带有数字.这些代表着来自5个不同选项的投票.布局是这样的:
I have a .txt file, say "results.txt" which contains 5 different options with a number behind. these represents like a voting from 5 different options. The layout is like this:
1|3
2|6
3|2
4|8
5|10
阶梯数是选项获得的票数.
The ladder number is how many votes the options has got.
我需要做的是对票数求和,将其增加1,然后回显结果:
What I need to do is to sum the votes, increase it by 1 and then echo the result:
echo "Total votes: 30 votes"
在这种情况下.
用于投票的表格是您的普通表格,有5种不同的选择:
The form which is used to voting is your normal and simple form with 5 different options:
<form action="aanestys.php" method="get">
Choose an option:
<select name="vote">
<option value=1 selected>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>
<br>
<input type="submit" value="Send">
</form>
您对此有任何提示或建议吗?我不一定需要一个直接的答案,因为我确实想学习使用fopen,fgets和fwrite命令,而不仅仅是复制/粘贴代码.
Do you have any tips or advice on how to do this? I don't necessarily need a straight answer because I do want to learn to use the fopen, fgets and fwrite commands and not just copy/paste codes.
看来,投票投给了通过表格选择的选项.并且.txt文件必须是最新的.到目前为止,我已经知道了:
It seems that the vote goes to an option which is selected with the form. And also that the .txt file must be up-to-date about it. So far I've got this:
<?php
$lines = file("results.txt");
$vote = $_GET['vote'];
$summa = 0;
$val = array();
foreach($lines as $line) {
$var;
$var = explode("|", $line);
if ($vote == $var[0]){
$var[1]++;
array_push($val, $var[0], "|", $var[1]);
} else {
array_push($val, $var[0], "|", $var[1]);
}
$summa = $summa += $var[1];
}
$ulos = implode("\n", $val) . "\n";
//Somehow, because this is an exercise, the checker says this is right
//although it's totally not even close to it.
echo "Total votes: $summa votes.";
file_put_contents("results.txt", $ulos);
?>
但是投票计数不正确.怎么了?
But the vote count isn't right. What's wrong about this?
推荐答案
使用 explode()
用定界符"|"将其相加,并通过每次加($var[1]
)将和存储在$sum
中.
Open the file with file()
, loop through the lines, explode()
it with the delimiter "|", and store the sum in $sum
by adding ($var[1]
) everytime.
<?php
$lines = file('file.txt');
$sum = 0 ;
foreach ($lines as $line){
$var = explode("|", $line);
$sum = $sum + $var[1];
}
echo $sum+1; //outputs 30
?>
希望这会有所帮助.
这篇关于来自文件的PHP总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!