constructing a multi-dimensional array of form inputs
PHP supports:
<input type=text name=array[]>
...and all values are just posted in that array. I want to do the same for a m开发者_如何学Cultidimensional? 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.
Try leaving the quotes away (name="response[q3][]") and then loop using foreach($_POST['response']['q3'] as $key => $value) { echo $value."\n"; }
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.
精彩评论