与阵列同名的单选按钮

时间:2017-06-15 13:39:20

标签: php html input

我有一个生成项目列表的表单,我希望能够为每个项目提供1-5分的分数。每个项表示一个表中的数据库插入,它通过另一个表中的相同ID链接。我需要让所有单选按钮具有相同的名称。我研究了一下,我发现你可以将它们命名为数组。我的问题是表单表的项目数量有所不同,具体取决于希望提交报告的组,我不能根据项目,得分[0],得分[1]使名称采用不同的索引。 ]等等。

HTML

<tr>
    <th>Indicador</th>
    <th>Peso</th>
    <th>Avaliação</th>
</tr>
<?php foreach($indicators as $indicator): ?>
    <?php echo "<tr>
        <td>". $indicator->indicator_name ."</td>
        <td>". $indicator->weight*100 ."%</td>
        <td>
            <label>
                1 <input value='1' name='score[]' type='radio'>
            </label>
            <label>
                2 <input value='2' name='score[]' type='radio'>
            </label>
            <label>
                3 <input value='3' name='score[]' type='radio'>
            </label>
            <label>
                4 <input value='4' name='score[]' type='radio'>
            </label>
            <label>
                5 <input value='5' name='score[]' type='radio'>
            </label>
        </td>
    </tr>";

?>
<?php endforeach; ?>

正如您可能已经知道的那样,每次单击单选按钮以获取其他项目时,前一项都会被取消选中。我将如何实现这一目标?还可以理解任何替代解决方案。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

然后使用$indicator->indicator_name而不是数字。任何唯一标识符都可以,只要它对该行是唯一的。

答案 1 :(得分:0)

您可以在数组内部设置项目的ID($indicator)。

如果我们假设id为$indicator->id,则您的代码可以是这样的:

<tr>
<th>Indicador</th>
<th>Peso</th>
<th>Avaliação</th>
</tr>
<?php foreach($indicators as $indicator): ?>
<?php echo "<tr>
    <td>". $indicator->indicator_name ."</td>
    <td>". $indicator->weight*100 ."%</td>
    <td>
        <label>
            1 <input value='1' name='score[".$indicator->id."]' type='radio'>
        </label>
        <label>
            2 <input value='2' name='score[".$indicator->id."]' type='radio'>
        </label>
        <label>
            3 <input value='3' name='score[".$indicator->id."]' type='radio'>
        </label>
        <label>
            4 <input value='4' name='score[".$indicator->id."]' type='radio'>
        </label>
        <label>
            5 <input value='5' name='score[".$indicator->id."]' type='radio'>
        </label>
    </td>
</tr>";
endforeach; ?>

表单提交后,您可以在另一个PHP脚本上收到这样的内容:

 echo $_POST['score'][$indicator->id];
相关问题