首页 > 解决方案 > 处理一个问题的多个动态答案数

问题描述

我有两张桌子,一张用来提问,另一张用来回答。每个问题可以有 3-5 个答案。

问题表:

_________________
| id | question |
|____|__________|
|  1 |    q1    |
|____|__________|

答案表:

__________________________________________
| id | answer | is_correct | question_id |
|____|________|____________|_____________|
|  1 |    a1  |     0      |      1      |
|____|________|____________|_____________|
|  2 |    a2  |     0      |      1      |
|____|________|____________|_____________|
|  3 |    a3  |     1      |      1      |
|____|________|____________|_____________|

在更新页面上,我想更新问题及其答案。

更新表格看起来像这样:

<input type="text" name="question"/>
<input type="text" name="answer-1"/>
<input type="text" name="answer-2"/>
<input type="text" name="answer-3"/>

在页面提交上,我试图获取答案值及其 ID。

我试过了:

foreach($_POST as $input){
    if (strpos($input, 'answer-') !== false) {
            $answers[] = $input;
    }
}

但通过这种方式,我得到的只是这些答案的值,而不是这些答案的 id。

我也试图给出所有的答案name="answers[]"。但这与我无法获得答案ID相同。

标签: php

解决方案


使用 foreach 循环语法,您可以同时访问数组的键和值,如下所示:

foreach($_POST as $inputName => $inputValue) {
    if (strpos($inputName, 'answer-') !== false) {
            $answers[] = $inputValue;
    }
}

推荐阅读