在数组中插入多个数组以存储在购物车CodeIgniter中

时间:2018-12-11 18:04:30

标签: php arrays codeigniter multidimensional-array frameworks

我从foreach循环中得到了这样的数组:

Array ( 
    [id] => 2 
    [qty] => 1 
    [price] => 130000 
    [name] => 0002/PNBP/411971/1/02/18 
) 
Array ( 
    [id] => 3 
    [qty] => 1 
    [price] => 120000 
    [name] => 0003/PNBP/411971/1/02/18 
) 
Array ( 
    [id] => 4 
    [qty] => 1 
    [price] => 150000 
    [name] => 0004/PNBP/411971/1/02/18 
)

我想像这样在数组中插入数据数组:

Array( 
    Array ( 
        [id] => 2 
        [qty] => 1 
        [price] => 130000 
        [name] => 0002/PNBP/411971/1/02/18 
    ), 
    Array ( 
        [id] => 3 
        [qty] => 1 
        [price] => 120000 
        [name] => 0003/PNBP/411971/1/02/18 
    ), 
    Array ( 
        [id] => 4 
        [qty] => 1 
        [price] => 150000 
        [name] => 0004/PNBP/411971/1/02/18 
    )
);

我尝试这样编码:

$data = array();
foreach ($_POST['id_kuitansi'] as $id_kuitansi){
    $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi);
    $i = $this->input;
    $data = array(
      'id' => $id_kuitansi,
      'qty' => '1',
      'price' => $detail_kuitansi['nilai'],
      'name' => $detail_kuitansi['no_kuitansi']
    );
    print_r($data);
    //$this->cart->insert($data);
}

3 个答案:

答案 0 :(得分:0)

尝试一下

$data = array();
foreach ($_POST['id_kuitansi'] as $id_kuitansi){
    $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi);
    $i = $this->input;
    $data[] .= array( 
      'id' => $id_kuitansi,
      'qty' => '1',
      'price' => $detail_kuitansi['nilai'],
      'name' => $detail_kuitansi['no_kuitansi']
    );
    print_r($data);
    //$this->cart->insert($data);
}

您只是简单地将每个值重新分配给$ data,而您需要将数组值附加到$ data数组

答案 1 :(得分:0)

此代码已解决问题:

foreach ($_POST['id_kuitansi'] as $id_kuitansi)
{
    $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi);
    $i = $this->input;
    $data[] = array(
      'id' => $id_kuitansi,
      'qty' => '1',
      'price' => $detail_kuitansi['nilai'],
      'name' => $detail_kuitansi['no_kuitansi']
    );
}
//print_r($data);
$this->cart->insert($data);

感谢穆罕默德...

答案 2 :(得分:0)

每当我们需要在单个查询中插入多个数据时,我们便可以用户批量插入数据。例如

$data = $arrInsert = array();
foreach ($_POST['id_kuitansi'] as $id_kuitansi){
    $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi);
    $i = $this->input;
    $data = array(
      'id' => $id_kuitansi,
      'qty' => '1',
      'price' => $detail_kuitansi['nilai'],
      'name' => $detail_kuitansi['no_kuitansi']
    );
    //print_r($data);
    $arrInsert[] = $data;
    //$this->cart->insert($data);
}
$this->db->insert_batch('tableName', $arrInsert);

在插入批处理中,您可以将tableName替换为表名。