我需要在mysql表中插入一个数组,带括号的行是我需要插入的例子。
Array
(
[0] => Array
(
[batch_id] => 1
[seq_id] => 1
[q_id] => 2046
[a1] => 0
[a2] => 1
[a3] => 2
[a4] => 3
[a5] => 4
)
[1] => Array
(
[batch_id] => 1
[seq_id] => 2
[q_id] => 2046
[a1] => 0
[a2] => 2
[a3] => 1
[a4] => 3
[a5] => 4
)
[2] => Array
(
[batch_id] => 1
[seq_id] => 3
[q_id] => 2046
[a1] => 2
[a2] => 0
[a3] => 2
[a4] => 2
[a5] => 1
)
表:
id | r_id | q_id | c_id | ranking
-------------------------------------------
18965| 2205 | 2046 | a1 | 0
18966| 2205 | 2046 | a2 | 2
18967| 2205 | 2046 | a3 | 3
18968| 2205 | 2046 | a4 | 1
18969| 2205 | 2046 | a5 | 4
19965| 2214 | 2046 | a1 | 0
19966| 2214 | 2046 | a2 | 1
19967| 2214 | 2046 | a3 | 1
19968| 2214 | 2046 | a4 | 2
19969| 2214 | 2046 | a5 | 3
(20965)| (11) | (2046) | (a1) | (0)
(20966)| (11) | (2046) | (a2) | (1)
(20967)| (11) | (2046) | (a3) | (2)
(20968)| (11) | (2046) | (a4) | (3)
(20969)| (11) | (2046) | (a5) | (4)
(21965)| (12) | (2046) | (a1) | (0)
(21966)| (12) | (2046) | (a2) | (2)
(21967)| (12) | (2046) | (a3) | (1)
(21968)| (12) | (2046) | (a4) | (3)
(21969)| (12) | (2046) | (a5) | (4)
(22965)| (13) | (2046) | (a1) | (2)
(22966)| (13) | (2046) | (a2) | (0)
(22967)| (13) | (2046) | (a3) | (2)
(22968)| (13) | (2046) | (a4) | (2)
(22969)| (13) | (2046) | (a5) | (1)
如果我想以这种方式插入它是否在插入状态中使用循环? Table.id是自动增量,r_id是batch_id + seq_id。
$result = $this->query("Select * from table_3");
$new_insert = array();
$csvr[] = $this->fetch_array($result);
foreach($csvr as $cr){
$ir_id = $cr['batch_id'].$cr['seq_id'];
$q_id = $cr['q_id'];
$query1 = "insert into t1 (id, survey_id, submitted) value ('$ir_id', '85',time());";
$this->query($query1);
foreach ($cr as $k => $v){
if(preg_match('{^a\d+$}',$k)){
$new_insert[] = array(
'r_id'=>$ir_id,
'q_id' =>$q_id,
'c_id' =>$k,
'ranking'=>$v
);
$query2 = "insert into Table (r_id, q_id, c_id, ranking) value ('r_id', 'q_id','c_id','ranking')";
$this->query($query2);
}
}
}
我不知道怎么做.....有人能帮助我吗?
答案 0 :(得分:1)
也许您正在寻找insert...values
(http://dev.mysql.com/doc/refman/5.7/en/insert.html):
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
答案 1 :(得分:1)
$row=array();
$row[]=array(
'batch_id' => 1,
'seq_id' => 1,
'q_id' => 2046,
'a1' => 0,
'a2' => 1,
'a3' => 2,
'a4' => 3,
'a5' => 4
);
$row[]=array(
'batch_id' => 2,
'seq_id' => 2,
'q_id' => 2047,
'a1' => 0,
'a2' => 1,
'a3' => 2,
'a4' => 3,
'a5' => 4
);
$insert_date =array();
foreach($row as $r){
$ir_id = $r['batch_id'].$r['seq_id'];
$q_id = $r['q_id'];
foreach($r as $k => $v){
if(preg_match('{^a\d+$}',$k)){ //update here
$insert_date[]=array(
'ir_id'=>$ir_id,
'q_id'=>$q_id,
'c_id'=>$k,
'ranking'=>$v
);
}
}
}
print_r($insert_date);
http://sandbox.onlinephpfunctions.com/code/78433f52466d56602eef2b01f668af23f6dd42f4
答案 2 :(得分:0)
foreach($row as $key => $r)
因此您可以将数组作为单独的变量进行管理