【问题标题】:Codeigniter Insert Batch arrayCodeigniter 插入批处理数组
【发布时间】:2017-08-19 06:54:30
【问题描述】:

我正在使用 Codeigniter 将多表单输入数据插入到数据库中。 我有这个帖子输入数组:

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

[question] => Array

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

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

我不明白如何将此数组转换为插入 如何使用插入批处理插入此数组。

$this->db->insert_batch('mytable', $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>

下面是我想要的数组格式。

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

【问题讨论】:

  • 在关于如何获取此数组的问题中发布您的代码?
  • 先生,我已经更新了问题。 @dhruvjadia
  • 先生,我再次更新了问题并添加了我需要的结果数组。 @dhruvjadia
  • 提供的答案

标签: php arrays codeigniter


【解决方案1】:

尝试如下:假设 $records 是您要插入的数组。

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];
    }

}

然后

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

【讨论】:

  • 您是否正确获得了$records['subject_id'][0] 的值。
  • 您发布的相关数组的名称是什么。
  • 我给它 $records = array();等等。
  • 先生,我再次更新了问题并添加了我需要的结果数组。 @hekmat
【解决方案2】:
<?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);

?>

【讨论】:

    猜你喜欢
    • 2017-04-01
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-26
    • 2013-07-07
    相关资源
    最近更新 更多