dongying3830 2011-05-07 07:05
浏览 67

构建表单输入的多维数组

PHP supports:

<input type=text name=array[]>

...and all values are just posted in that array. I want to do the same for a multidimensional? array, however I am getting slightly lost in trying to extract data.

I have a set of questions, most have one answer (radio buttons) however some are multi-response (checkboxes). I want to be able to store all answers in one multidimensional array so it may appear like this:

question 1 | answer |
question 2 | answer |
question 3 | answer |
question 3 | answer |
question 3 | answer |
question 4 | answer |

So, I am doing this:

<input name="response['q1'][]" type=text value=''>
<input name="response['q2'][]" type=text value=''>
<input name="response['q3'][]" type=text value=''>
<input name="response['q3'][]" type=text value=''>

Now how can I go about extracting this data for storing into my mysql db. Ive been playing around with a foreach, however when it is the case there is more than one answer for a question (q3 lets say) I can't get that data in my loop.

  • 写回答

1条回答 默认 最新

  • dongqiao3833 2011-05-07 07:14
    关注

    Try leaving the quotes away (name="response[q3][]") and then loop using foreach($_POST['response']['q3'] as $key => $value) { echo $value." "; }

    foreach($_POST['response'] as $question => $answer) {
      if(count($answer) > 1) {
        foreach($answer as $key => $value) {
          //loop your multiple answers here
        }
      } elseif(count($answer) == 1 {
         // 1 answer found for $_POST['response'][ $question ];
      } else {
        // no answer found.. (perhaps $_POST['response'][ $key ] is a value and no array.
      }
    }
    

    I guess this is what you're looking for.

    评论
    编辑
    预览

    报告相同问题?

    手机看
    程序员都在用的中文IT技术交流社区

    程序员都在用的中文IT技术交流社区

    专业的中文 IT 技术社区,与千万技术人共成长

    专业的中文 IT 技术社区,与千万技术人共成长

    关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

    关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

    客服 返回
    顶部