【问题标题】:passing a multi dimensional array to Insert in Codeigniter Model将多维数组传递给 Codeigniter 模型中的 Insert
【发布时间】:2018-01-21 01:36:34
【问题描述】:
{
    "word": ["w1", "w2"],
    "meaning": ["m1", "m2"],
    "parts_of_speech": ["p1", "p2"],
}

这是我在模型中拥有的数据,现在分配给 $data 变量

在上面的$data中,每个word索引在meaning数组中都有对应的含义,每个word索引都有parts_of_speech 数组索引中对应的 parts_of_speech。这样,word,meaning,parts_of_speech数组的长度始终保持不变

我尝试了以下方法插入表格

$this->db->insert('table_words', $data); 

$this->db->insert_batch("table_words",$data);

但它发生了错误

【问题讨论】:

标签: php codeigniter multidimensional-array model associative-array


【解决方案1】:

CodeIginter 接受要插入的数组,其中键应该是“列名”,值应该是我们要插入的记录。据我所知,您必须插入多行,因此您必须使用批量插入。 试试下面的代码:

$data = array(
   array(
      'word' => 'w1' ,
      'meaning' => 'm1' ,
      'parts_of_speech' => 'p1'
   ),
   array(
      'word' => 'w2' ,
      'meaning' => 'm2' ,
      'parts_of_speech' => 'p2'
   )
);
$this->db->insert_batch('mytable', $data); 

你的json应该是这样的

[{"word":"w1","meaning":"m1","parts_of_speech":"p1"},{"word":"w2","meaning":"m2","parts_of_speech":"p2"}]

【讨论】:

  • 如何从控制器生成这个 $data 数组
  • 您的数据应该像上面的格式以便插入。 Codeigniter 支持在数组上方插入。像上面那样制作你的 json 格式,然后在数组中解码它。之后,您只需传递该数组。
  • @MithunSudheendran 在这里为可能遇到相同问题的人发布您的答案。
猜你喜欢
  • 1970-01-01
  • 2018-02-10
  • 2012-10-12
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
  • 2014-01-06
  • 2021-03-06
  • 1970-01-01
相关资源
最近更新 更多