dqyat62284 2011-02-08 23:41
浏览 25
已采纳

单选按钮,多维数组和PHP

I have created a form that allows someone to create a quiz, all of the questions and the answers are stored in a database. You can see a simplified version of the form here:

http://jsfiddle.net/superuntitled/uaTtx/4/

Each question can have an infinite number of answers and only one answer can be correct. To denote the 'correct' answer, I am using radio buttons.

The problem that I am having is that only the selected radio button passes a value to my php code, see a sample $_POST array of values (in this example, three answers for the question "What is a space station?"):

[text] => Array
    (
        [0] => A cosmic hotel
        [1] => An interstellar depot
        [2] => A closet organizer
    )

[correct] => Array
    (
        [0] => 1
    )

Even if the correct answer was "An interstellar depot", the first answer "A cosmic hotel" will be entered as the correct answer when I loop through this $_POST array. This is because only a selected radio button will pass a value.

My radio input looks like this:

<input  type="radio" name="answer[1][correct][]" value="1" />

The first set of brackets denotes the question it is associated with, and this number is incremented with each new question.

Does anyone have any ideas on how set the correct answer properly?

  • 写回答

3条回答 默认 最新

  • doubu1970 2011-02-09 03:22
    关注

    Okay, I think I get it now. But I'm afraid there is no easy solution to your problem.

    While the ..[] syntax works for collecting the text fields in an array, there is no correlation between text inputs and radio inputs. You have to manually name the text fields answer[1][text][235] and the radios answer[1][correct][235].

    This requires an enumeration loop for the PHP output. And also obviously that the DHTML/AJAX "Add another answer/question" function has to parse the existing fields, and count the last number up.

    If you want to retain the lazy solution, then you have to use type=checkbox instead of type=radio. That's the only way to have all fields present at submission, so the automatic ...[] enumeration works for text fields and checkboxes.
    You could use some DHTML/Javascript trickery there to ensure that only one checkbox per group is selected at any time. (= fake radio buttons)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办