Codeigniter Insert Batch array

久未见 提交于 2021-01-01 13:53:04

问题


I am Inserting a multiple form input data in to database using Codeigniter. I have this post input array:

 Array
(
 [subject_id] => Array
    (
        [0] => 1
        [1] => 1
    )

[question] => Array

    (
        [0] => test
        [1] => test2
    )

[option1] => Array
    (
        [0] => test
        [1] => test2
    ) )

I don't get that how do i convert this array to insert How to insert this array using Insert batch.

$this->db->insert_batch('mytable', $data);

This is the form code which i use for posting the data:

                <form method="post">
            <input type="text" name="subject_id[]" >
            <input type="text" name="question[]" >
            <input type="text" name="record[]" >

            // Down side Part is appended when user want to add more question

            <input type="text" name="subject_id[]" >
            <input type="text" name="question[]" >
            <input type="text" name="record[]" >

            <input type="submit" name="submit" >
            </form>

Below is the Array format which i want.

$data = array(
            array(
                'subject_id' => 'My title' ,
                'question' => 'My Name' ,
                'option1' => 'My date'
                ),
            array(
                'subject_id' => 'Another title' ,
                'question' => 'Another Name' ,
                'option1' => 'Another date'
                )
            );

回答1:


<?php
    $i = 0;
    foreach($subject_id as $key=>$val)
    {
          $data[$i]['subject_id'] = $val;
          $data[$i]['question'] = $question[$key];
          $data[$i]['option1'] = $record[$key];
          $i++;
    }
    $this->db->insert_batch('mytable', $data);

?>



回答2:


Try like below:Assume $records is an array that you want to insert.

foreach ($records as $record) 
{

    for ($i=0; $i < count($record); $i++) 
    {   
    $data[$i]['subject_id'] = $record['subject_id'][$i];
    $data[$i]['question'] = $record['question'][$i]
    $data[$i]['option1'] = $record['option1'][$i];
    }

}

Then

$this->db->insert_batch('mytable', $data);


来源:https://stackoverflow.com/questions/43031620/codeigniter-insert-batch-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!