代码之家  ›  专栏  ›  技术社区  ›  Prashanth kumar

使用PHP从HTML表单获取“n”个无线电选项的有效方法

  •  0
  • Prashanth kumar  · 技术社区  · 7 年前

    使用PHP,我知道如何在操作页面中获取结果。

    <html>
    <body>
    <form action = "result.php">
    Question 1:
    <input type='radio' name='Q1' value='Op1' /> Op1
    <input type='radio' name='Q1' value='Op2' /> Op2
    <input type='radio' name='Q1' value='Op3' /> Op3
    <input type='radio' name='Q1' value='Op4' /> Op4
    
    Question 2:
    <input type='radio' name='Q2' value='Op1' /> Op1
    <input type='radio' name='Q2' value='Op2' /> Op2
    <input type='radio' name='Q2' value='Op3' /> Op3
    <input type='radio' name='Q2' value='Op4' /> Op4
    .
    .
    .
    .
    </form>
    </body>
    </html>
    

    <?PHP
    $answer1 = $_POST['Q1'];
    $answer2 = $_POST['Q2'];
    .
    .
    ?>
    

    这看起来一点都不整洁,是否有任何有效的方法来获取在前端为所有这些问题选择的选项,而不是写20条语句。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Phil    7 年前

    例如

    <input type="radio" name="radio[Q1]" value="Op1">
    <input type="radio" name="radio[Q1]" value="Op2">
    
    <input type="radio" name="radio[Q2]" value="Op1">
    <input type="radio" name="radio[Q2]" value="Op2">
    

    foreach

    foreach($_POST['radio'] as $question => $answer) {
        // $question will be "Q1", "Q2", etc
        // $answer will be the chosen radio button value
    }
    

    "radio"


    <form> 应该有 method="post"

    推荐文章