将数组存储在数据库中

时间:2014-08-08 08:01:21

标签: php mysql codeigniter

我有三个数组示例:$ array1,$ array2,$ array3。

我想将array2和array3插入同一个表中的两个不同列中。 我可以这样做吗?

这里是我正在尝试的下面的代码但是它对我来说不起作用我在codeigniter中做了:

  • 控制器:

     $athletes_id = $this->input->post('athletes'); // array 1
     $fields_id = $this->input->post('fields_id');  // array 2
     $athlete_score = $this->input->post('athlete_score');  // array 3
    
    
     $id = array();
     foreach($athlete_score as $row){
     $additional_data = array(
     'test_reports_id' => $test_report_id,
     'score' => $row,
     );
     $id[] = $this->test_model->save_test_reports_details($additional_data);
     }
     for($j=0;$j<count($fields_id);$j++){
     $data2 = array('fields_id' => $fields_id[$j]);
     $this->test_model->update_test_reports_details($id,$data2);
     }
    
  • 型号:

       public function update_test_reports_details($id,$data2){
       $this->db->where_in('id',$id);
       $this->db->update('test_reports_details',$data2);
       }
    

3 个答案:

答案 0 :(得分:2)

只需序列化数组。

$data2 = serialize($array2); // or whatever array you want to store

然后使用unserialize检索

$array2 = unserialize($data2);//or the row index  

答案 1 :(得分:0)

要在数据库中存储数组,您必须将其序列化。

尝试:

public function update_test_reports_details($id,$data2){
$this->db->where_in('id',$id);
$this->db->update('test_reports_details',serialize($data2));
}

要从数据库中获取它时要反序列化它必须使用unserialize()

答案 2 :(得分:0)

您可以按照其他答案中的建议进行序列化,但我个人更喜欢对阵列进行json_encode。

$data = json_encode($array);

当您在模型中阅读时,您应该解码数据:

$array = json_decode($data, true); // set second argument to true to get an associative array

使用JSON具有更好的可读性,同时仍然在数据库中。这可能看起来不多,但在某些情况下它确实有用。

相关问题