官方演示案例,比較傻瓜不能靈活使用
$data=array(array('title'=>'My title','name'=>'My Name','date'=>'My date'),array('title'=>'Another title','name'=>'Another Name','date'=>'Another date'));
$this->db->insert_batch('mytable',$data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'),? ('Another title', 'Another name', 'Another date')
第一個參數(shù)為要插入的表名,第二個參數(shù)為要插入的數(shù)據(jù),是個二維數(shù)組。
我再此將指導大家如何拼接數(shù)組來完成批量數(shù)據(jù)的添加
方案:
很多人喜歡通過循環(huán)的方式來添加數(shù)據(jù),比如循環(huán)100次,添加100條數(shù)據(jù),效率慢
我們使用循環(huán)將100次的數(shù)據(jù)集來拼接為數(shù)組,一次完成添加效率快
$Randarray = array(); ?//定義空數(shù)組
foreach ($randQuery->result() as $row) //循環(huán)定義數(shù)組
{
$item = array();
$item['id'] = $id;
$item['title'] = $title;
$Randarray[] = $item;//將數(shù)組參數(shù)循環(huán)添加到空數(shù)組中
}
$this->db->insert_batch('lqr_quanzi_dianzan', $Randarray);
此案例針對ci的 其他框架可以根據(jù)不同的邏輯想修改部分代碼即可。