You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在提交更新表单时获取关联答案的id与值,实现问题及答案同步更新

解决方案

方案1:使用带索引的数组命名(推荐)

直接把答案输入框的name属性设置为带答案ID的数组格式,后端接收时可以直接拿到ID和对应值:

修改后表单代码:

<input type="text" name="question"/>
<!-- 以下输入框中[]内的数字就是对应答案的ID,渲染页面时动态替换成实际的answer_id即可 -->
<input type="text" name="answers[1]"/>
<input type="text" name="answers[2]"/>
<input type="text" name="answers[3]"/>

后端接收代码:

// 直接获取answers数组,键是答案ID,值是答案输入内容
$answers = $_POST['answers'] ?? [];
foreach ($answers as $answerId => $answerContent) {
    // 在这里处理每个答案的更新逻辑即可
    // 比如执行update answers set answer = ? where id = ? 绑定$answerContent和$answerId
}

如果需要同时提交is_correct这类其他答案属性,还可以用二维数组,格式为name="answers[1][answer]"、name="answers[1][is_correct]",后端会自动解析为每个ID对应的属性集合,更灵活。


方案2:修改原有遍历逻辑(兼容现有命名方式)

你之前的写法只遍历了$_POST的值,没有遍历键,只要改成遍历键值对就能从name属性里提取答案ID:

$answers = [];
foreach($_POST as $key => $inputValue){
    if (strpos($key, 'answer-') === 0) { // 这里判断前缀要匹配键,不是匹配值
        $answerId = str_replace('answer-', '', $key);
        $answers[$answerId] = $inputValue;
    }
}

内容的提问来源于stack exchange,提问作者user_411

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 08:15:05