我正在尝试使用以下类型的输入创建一个测验表单:
<input type="date" name="Q1"/>
<input type="checkbox" id="2a" name="Q2[]"/>
<input type="checkbox" id="2b" name="Q2[]"/>
<input type="checkbox" id="2c" name="Q2[]"/>
<input type="radio" name="Q3a"/>
<input type="radio" name="Q3b"/>
<input type="radio" name="Q3c"/>
<input type="radio" name="Q4a"/>
<input type="radio" name="Q4b"/>
在 php 中,我想获取这些输入并使用for
循环检查它们的答案:
$answer = array(//a whole bunch of answers);
for ($i=0; $i<6; $i++){
$response = $_POST["Q".$i];
$response = sanitise_input($response);
if (in_array($response, $answer)){
$point++;
}
}
echo($point);
这个的基本概念是有效的,但是Q2,3和4呢?Q2 有 [],Q3 和 Q4 在 name 属性中有 a、b 和 c(不在 Q4 中(,我不知道如何编码,以便如果找不到"Q".$i
,请尝试查找"Q".$i."[]"
、"Q".$i."a"
等等......
提前致谢
编辑:好的,所以按照建议,我已将输入名称更改为
<input type="date" name="Q1"/>
<input type="checkbox" id="2a" name="Q2[]"/>
<input type="checkbox" id="2b" name="Q2[]"/>
<input type="checkbox" id="2c" name="Q2[]"/>
<input type="radio" name="Q3[a]"/>
<input type="radio" name="Q3[b]"/>
<input type="radio" name="Q3[c]"/>
<input type="radio" name="Q4[a]"/>
<input type="radio" name="Q4[b]"/>
这意味着我需要一种不同的方法来给这些问题一个标记,因为它们是在数组中返回的,我认为in_array仍然不会处理这个问题。
我认为最好更改名称。
<input type="date" name="Q1"/>
<input type="checkbox" id="2a" name="Q2[]"/>
<input type="checkbox" id="2b" name="Q2[]"/>
<input type="checkbox" id="2c" name="Q2[]"/>
<input type="radio" name="Q3[a]"/>
<input type="radio" name="Q3[b]"/>
<input type="radio" name="Q3[c]"/>
<input type="radio" name="Q4[a]"/>
<input type="radio" name="Q4[b]"/>
试试这个:
$answer = array(/*a whole bunch of answers*/);
$firstQuestionIndex = 1;
$maxQuestions = 100000;
$step = 1;
for ($i = $firstQuestionIndex; $i < $maxQuestions; $i++) {
switch($step) {
case 1:
if(isset($_POST["Q".$i]) && !empty($_POST["Q".$i])) {
$response = $_POST["Q".$i];
$response = sanitise_input($response);
if (in_array($response, $answer)){
$point++;
}
} else {
$step++;
$i = $firstQuestionIndex - 1;
}
break;
case 2:
if(isset($_POST["Q".$i.'[]']) && !empty($_POST["Q".$i.'[]'])) {
$response = $_POST["Q".$i.'[]'];
$response = sanitise_input($response);
if (in_array($response, $answer)){
$point++;
}
} else {
$step++;
$i = $firstQuestionIndex - 1;
}
break;
default:
for ($j = 0; $j < $maxQuestions; $j++) {
if(isset($_POST["Q".$i.chr($j+ord('a'))]) && !empty($_POST["Q".$i.chr($j+ord('a'))])) {
$response = $_POST["Q".$i.chr($j+ord('a'))];
$response = sanitise_input($response);
if (in_array($response, $answer)){
$point++;
}
} else {
if($j == 0) {
$i = $maxQuestions;
} else {
$i = $firstQuestionIndex - 1;
}
$j = $maxQuestions;
}
}
break;
}
}
echo($point);
好的,我已经解决了使用此页面将数组作为响应的问题的给出标记
for ($i=1; $i<=4; $i++){
$response = $_POST["Q".$i];
if (in_array($response, $answer)){
$point++;
} elseif (count(array_diff($_POST["Q".$i], $answer)) == 0){
$point++;
}
}