我在我的表单中有以下编码。如何获取提交内部循环的所有单选按钮值的值?或者给我任何其他解决方案。
<form action="res.php" method="post">
<?php
for($i=1;$i<=5;$i++)
{
?>
<div class="well well-sm well-primary">
<input type="hidden" name="ques"/>Questions?
</div>
<div class="well well-sm">
<div class="radio">
<label>
<input type="radio" name="optradio<?php echo $i; ?>" value="a">Option 1
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optradio<?php echo $i; ?>" value="b">Option 2
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optradio<?php echo $i; ?>" value="c">Option 3
</label>
</div>
</div>
<?php
}
?>
<button type="submit" class="btn btn-success" name="submit">Finish</button>
</form>
答案 0 :(得分:7)
使用单选按钮数组如下
<form method="post">
<?php
for($i=1;$i<=5;$i++)
{
?>
<div class="well well-sm well-primary">
<input type="hidden" name="ques"/>Questions?
</div>
<div class="well well-sm">
<div class="radio">
<label>
<input type="radio" name="optradio[<?php echo $i; ?>]" value="a">Option 1</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optradio[<?php echo $i; ?>]" value="b">Option 2</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optradio[<?php echo $i; ?>]" value="c">Option 3</label>
</div>
</div>
<?php
}
?>
<button type="submit" class="btn btn-success" name="submit">Finish</button>
</form>
要访问发布的值,您只需使用$_POST['optradio']
考虑选择5个问题选项1,选项2,选项3,选项1,选项2
POST['optradio']
将提供类似
数组([1] =&gt; a [2] =&gt; b [3] =&gt; c [4] =&gt; a [5] =&gt; b)
要从此数组中访问sigle值,可以使用foreach
loop as,
<?php
foreach($_POST['optradio'] as $option_num => $option_val)
echo $option_num." ".$option_val."<br>";
?>
答案 1 :(得分:2)
使用一个隐藏输入来存储for循环中的单选按钮名称数组 像
<input type="hidden" name="testradio[]" value="optradio<?php echo $i; ?>">
然后使用foreach
获取单选按钮值$rdobtn = $_POST['testradio'];
$idx = 0;
foreach($rdobtn as $val){
$rdovalue = $val[$idx];
// perform opertation using above $rdovalue variable.
$idx++;
}
}
答案 2 :(得分:1)
是的,正如肖恩评论的那样,试试这个:
<form action="res.php" method="post">
<?php
for($i=1;$i<=5;$i++)
{
?>
<div class="well well-sm well-primary">
<input type="hidden" name="ques"/>Questions?
</div>
<div class="well well-sm">
<div class="radio">
<label>
<input type="radio" name="optradio[<?php echo $i; ?>]" value="a">Option 1
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optradio[<?php echo $i; ?>]" value="b">Option 2
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optradio[<?php echo $i; ?>]" value="c">Option 3
</label>
</div>
</div>
<?php
}
?>
<button type="submit" class="btn btn-success" name="submit">Finish</button>
</form>
然后在PHP端使用下面的单选按钮值为:
foreach ($_POST['optradio'] as $optNum => $option) {
// do stuff with $optNum and $option
}
答案 3 :(得分:1)
试试这个:
<input type="radio" name="optradio[]" value="a">
在PHP文件中,
$_POST['optradio']
将作为数组生成。