[英]Radio buttons in foreach loop
我从数据库中提取了一系列问题,需要为每个问题循环单选按钮。 我需要将所有答案返回到一个看起来像这样的数组
$answer_grp1 = array("T", "T", "T");
我的代码看起来像这样。 将数组放入$ _POST ['answer_grp1']的正确(name = ??)语法是什么
<?php foreach ($questions as $question):
if ($question['q_type']==1): ?>
<tr>
<td style="width:5%;"><?= $question['q_number'] ?></td>
<td style="width:15%;">
T<input type="radio" name=answer_grp1[] value="T" />
F<input type="radio" name=answer_grp1[] value="F" />
</td>
<td><?= $question['q_text'] ?></td>
</tr>
<?php endif;
endforeach; ?>
我倾向于使用for循环代替:
<?php
for ($i = 0; $i < count($questions); $i++) {
$question = $questions[$i];
if ($question['q_type']==1): ?>
<tr>
<td style="width:5%;"><?= $question['q_number']; ?></td>
<td style="width:15%;">
T<input type="radio" name=answer_grp1[<?php print $i; ?>] value="T" />
F<input type="radio" name=answer_grp1[<?php print $i; ?>] value="F" />
</td>
<td><?= $question['q_text']; ?></td>
</tr>
<?php endif;
endfor; ?>
这是你的代码:
<?php
$i = 0;
foreach ($questions as $question):
if ($question['q_type']==1): ?>
<tr>
<td style="width:5%;"><?= $question['q_number']; ?></td>
<td style="width:15%;">
T<input type="radio" name=answer_grp1[<?php print $i; ?>] value="T" />
F<input type="radio" name=answer_grp1[<?php print $i; ?>] value="F" />
</td>
<td><?= $question['q_text']; ?></td>
</tr>
<?php endif; ?>
<?php
$i++
endforeach; ?>
你会用的
$_POST['answer_grp1'][0]
$_POST['answer_grp1'][1]
... 等等。
如果所有答案都在这个数组中,你也可以像这样循环:
for ($x=0; $x<count($_POST['answer_grp1']); $x++)
{
$value = $_POST['answer_grp1'][$x];
}
只要所有字段都在一个<form>
标记内并且您提交表单,那么该数组应该在$_POST
全局中可用。
您对每个输入的命名, answer_grp1[]
是正确的; 但是你应该在名称周围添加引号。
您还应该在问题输出后添加分号 - 更改此:
<?= $question['q_text'] ?>
对此:
<?= $question['q_text']; ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.