如果所有数组都有值,我有这些代码将数组插入db。问题是,如果一个或多个数组没有值,它仍会插入到db但当然具有空值。有人可以请帮助我如何制定一个条件,只有那些有值的samp_id
才会被插入到db中,所以我没有空值行。提前谢谢。
这是我的控制器:
public function save_section_test1() {
//echo '<pre>';print_r($_POST);die;
$samp = $this->input->post('samp');
$quantity = $this->input->post('quantity');
$specify = $this->input->post('specify');
$save_sect = array(
array(
'emp_id' => $this->input->post('emp_id'),
'section_id' => $this->input->post('section'),
'test_id' => $this->input->post('drop_molec'),
'samp_id' => $samp[0],
'quantity' => $quantity[0],
'specification' => $specify[0],
),
array(
'emp_id' => $this->input->post('emp_id'),
'section_id' => $this->input->post('section'),
'test_id' => $this->input->post('drop_molec'),
'samp_id' => $samp[1],
'quantity' => $quantity[1],
'specification' => $specify[1],
),
array(
'emp_id' => $this->input->post('emp_id'),
'section_id' => $this->input->post('section'),
'test_id' => $this->input->post('drop_molec'),
'samp_id' => $samp[2],
'quantity' => $quantity[2],
'specification' => $specify[2],
),
);
foreach ($save_sect as $save){
$this->db->insert('tblsavesection', $save);
}
redirect(base_url('user/show'));
}
答案 0 :(得分:1)
当您拥有insert_batch()
foreach
要删除没有键sampl_id
值的子数组,可以使用array_filter()
,
例如:
$data = array_filter($array,function($item) {return !empty($item['sampl_id']);});
// then insert
if(!empty($data)){
$this->db->insert_batch('your_table', $data);
}else{
echo 'seems not even single item has valid sampl_id';
}
答案 1 :(得分:0)
更新。我现在可以根据数组的数量插入到db。现在的问题是我收到错误消息,指出所有没有值的数组都是“Undefined offset”。但插入到db函数工作正常。
更新我的foreach foreach($ save_sect as $ save){
public static void MakeChanges(MappingFileModel modelWithChanges)
{
var deleteIndex = -1;
for (var i =0; i<Mapping.Count; i++)
{
if (Mapping[i].ScanIndex.Equals(modelWithChanges.ScanIndex))
{
if (modelWithChanges.Column == -1)
{
deleteIndex = i;
}
}
}
if (deleteIndex != -1)
{
Mapping.RemoveAt(deleteIndex);
}
}