用于php表单的多个单选按钮数组

tan*_*ira 0 html php forms arrays radio-button

我是新手.我正在研究网络开发,并且必须为问卷创建一个php响应表单,然后输入到数据库中.我在单选按钮上遇到了麻烦.我无法创建构成数组的正确代码并在响应表单/页面中显示答案.

这是我的代码:

<form name="modulequestionnaire" method="post" action="tania.responseform.php" />

<p><i>Rate each question from 6 to 1, six being strongly 
agree and one being strongly disagree.</i></p>

1. I think the module guide/student handbook provided enough information about the 
module content, organisation and assessment.<br/>

6<input type="radio" name="answer[1]" value="6"> 5<input type="radio" name="answer[1]" value="5"> 
4<input type="radio" name="answer[1]" value="4"> 3<input type="radio" name="answer[1]" value="3"> 
2<input type="radio" name="answer[1]" value="2"> 1<input type="radio" name="answer[1]" value="1">
</p>

2.The module was well organised.<br/>

6<input type="radio" name="answer[2]" value="6"> 5<input type="radio" name="answer[2]" value="5"> 
4<input type="radio" name="answer[2]" value="4"> 3<input type="radio" name="answer[2]" value="3"> 
2<input type="radio" name="answer[2]" value="2"> 1<input type="radio" name="answer[2]" value="1"> 
</p>

3.The Learning Resource Centre provided adequate materials for the module.<br/>

6<input type="radio" name="answer[3]" value="6"> 5<input type="radio" name="answer[3]" value="5"> 
4<input type="radio" name="answer[3]" value="4"> 3<input type="radio" name="answer[3]" value="3"> 
2<input type="radio" name="answer[3]" value="2"> 1<input type="radio" name="answer[3]" value="1"> 
</p>
Run Code Online (Sandbox Code Playgroud)

我知道答案可能与isset函数有关,但我不知道如何编写代码.有人可以教我或帮助我吗?

sja*_*agr 5

当您不确定如何处理已设置的HTML标记时,您应该var_dump($_POST)将发送到PHP处理程序页面的值放在一起,这样您就可以知道格式的样子,从而可以从那里开始.

当我创建HTML并使用var_dump一些随机选择对其进行测试时,输出为

array(2) { ["answer"]=> array(3) { [1]=> string(1) "5" [2]=> string(1) "3" [3]=> string(1) "4" } ["submit"]=> string(6) "Submit" }
Run Code Online (Sandbox Code Playgroud)

请注意,$_POST['answer']变量中有一个数组.因此,您应该foreach遍历该数组中的每个元素来处理每个相应的值:

foreach ($_POST['answer'] as $answer) {
    // do stuff with the answer
}
Run Code Online (Sandbox Code Playgroud)

如果需要使用在POST数组中定义的答案编号,可以foreach使用键:

foreach ($_POST['answer'] as $answerNum => $answer) {
    // do stuff with $answerNum and $answer
}
Run Code Online (Sandbox Code Playgroud)

当然,您可以直接通过其编号访问您的答案:

if (!empty($_POST['answer'][1])) { // To ensure that the value is being sent
    // do stuff with $_POST['answer'][1]
}
Run Code Online (Sandbox Code Playgroud)