我在输入字段文本框中有两个以逗号分隔的值,answers
和qid
作为输入名称。
answers = abc,def,ghi
qid = 1,2,3
我想如何插入:
qid|answer
--------------
1|abc
2|def
3|ghi
但根据代码,它同样为所有3个qids插入abc
对于所有3个qids,def
和ghi
,这样我得到9个元组而不是3个。
代码:
$answers=$this->input->post("answers");
$question=$this->input->post("qid");
$ans = explode(',',$answers);
$qid = explode(',',$question);
foreach($qid as $qids){
foreach($ans as $anss){
$data = array(
'qid' => $qids,
'user_answer'=>$anss,
);
$result = $this->db->insert("user_answer",$data);
}
}
答案 0 :(得分:0)
您只需要一个 foreach循环
注意:仅当 $ ans 和 $ qid 记录匹配时才有效(两个数组中的记录数相同),否则可能行为不端!
$answers=$this->input->post("answers");
$question=$this->input->post("qid");
$ans = explode(',',$answers);
$qid = explode(',',$question);
foreach($qid as $k => $qids){
$data = array(
'qid' => $qids,
'user_answer'=>$ans[$k],
);
$result = $this->db->insert("user_answer",$data);
}