所以,我正在为我的网页创建一个调查,我正在使用一个文本文件来存储结果:
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28
我必须使用PHP从文本文件中提取结果并将其显示给用户。该调查仅包括单选按钮(用户可以选择的选项)。每个数字代表该单选按钮的结果。无论如何,我的问题是阅读文本文件。当它只是一个数字(12345678 ...)时,我可以使它工作,但如果需要,它不会将它们显示为两位数。问题是如何让php不包含“|”如果需要,还会将数字显示为两位数?我是php的新手。
此外,如果新用户提交表单,我最终将阅读该文件以更新结果,但是现在我只是想让它显示正确。这是我的代码:
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
setcookie("Submit", "yes");
}
// the file that will store the data
$fileName = "data/results.txt";
$republican = 0;
$democratic = 0;
$libertarian = 0;
$right = 0;
$wrong = 0;
$undecided = 0;
$trump = 0;
$hilary = 0;
$mucmullin = 0;
$otherVote = 0;
$wontVote = 0;
$debateYes = 0;
$debateNo = 0;
$changeYes = 0;
$changeNo = 0;
$age1829 = 0;
$age3044 = 0;
$age4559 = 0;
$age60 = 0;
$cauc = 0;
$afAm = 0;
$his = 0;
$natAm = 0;
$other = 0;
$male = 0;
$female = 0;
//$results = fopen($fileName, "a+") or die("Unable to save results of your survey.");
//Check to see if we got here from POST
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//open file
//save file content as an int variable, or could save it as an array
// close file
// check all radio buttons and see if the it was selected,
// if so then ++ the variable we got from text file.
// save data to the text file
//display results
$formPost = TRUE;
} else { /* This will only excute if the user did not submit the form */
// delcare array that will store the contents of the text file
$results = array();
// open file and read it into the array
$results = readTextFile($fileName);
}
/*********************************************
* READ TEXT FILE FUNCTION
* This section will get data from from the file.
* It will simply read it, and won't be able to edit
* the file at all. It will store the contents,
* of the file into an array, and then close the
* file.
*********************************************/
function readTextFile($fileName) {
// declaring local array
$results = array();
// open file
$file = fopen($fileName, "r");
// read the file
while (!feof($file)) {
$results[] = fgetc($file);
}
// I wasn't born in a barn
fclose($file);
// make like a leaf
return $results;
}
?>
答案 0 :(得分:0)
阅读整个文件,然后使用explode
函数按如下方式将结果字符串拆分为|
个字符。
$results = file_get_contents($fileName);
$results = explode("|", $results);
数组$results
将包含原始字符串中由|
分隔的所有数字(作为字符串)。
如果那时你需要找出数组是否包含数字 - 例如是否选择了单选按钮1 - 您可以创建第二个数组,如下所示:
$results2 = [];
foreach ($results as $num) {
$results2[$num] = true;
}
然后,您应该能够检查$results2[1]
,如果选择了单选按钮1,它将是true
。