使用json_encode在数据库中插入值的问题

时间:2011-09-25 17:43:27

标签: php arrays codeigniter json

我希望在一行数据库表中插入,使用以下php代码(foreach)后面的值,但是在插入获取以下错误后,我该怎么办?

值:

<div class="column">
    <input type="text" name="start_date[1][]" value="1111">
    <input type="text" name="end_date[1][]" value="1111">
    <input type="text" name="price_change[1][]" value="1111">
</div>
<div class="column">
    <input type="text" name="start_date[2][]" value="2222">
    <input type="text" name="end_date[2][]" value="2222">
    <input type="text" name="price_change[2][]" value="2222">
</div>
<div class="column">
    <input type="text" name="start_date[3][]" value="3333">
    <input type="text" name="end_date[3][]" value="3333">
    <input type="text" name="price_change[3][]" value="3333">
</div>

Php代码:

    $residence_ups_input = $this->input->post('start_date');
    $residence_upe_input = $this->input->post('end_date');
    $residence_upc_input = $this->input->post('price_change');
    var_dump($residence_ups_input); // output this is: nobool(false)
    $residence_p = array();
    foreach ($residence_ups_input as $idx => $name) { //line 134        
        $residence_p[] = array(
            'start_date' => $residence_ups_input[$idx],
            'end_date' => $residence_upe_input[$idx],
            'price_change' => $residence_upc_input[$idx]
        );
    }
    ;
    $data = array(
        //'name' => $this -> input -> post('name'),
        'residence_p' => json_encode($residence_p)
    );
    $this->db->insert('tour_foreign', $data);

错误:

  

遇到PHP错误
严重性:警告
消息:无效   为foreach()提供的参数
文件名:inser.php
直线   编号:134

3 个答案:

答案 0 :(得分:0)

替换

 foreach ($residence_ups_input as $idx => $name) { 

 foreach (get_object_vars($residence_ups_input) as $idx => $name) { 

您正在将对象传递给foreach,它需要一个关联数组。从现在开始

json_decode($string, true)

而不是

json_decode($string)

并像这样访问变量:

$var['key'];
而不是     $ VAR-&GT;键

答案 1 :(得分:0)

$residence_ups_input变量不是数组

使用此代码:

array_push($residence_ups_input,$this->input->post('start_date'));
array_push($residence_upe_input,$this->input->post('end_date'));
array_push($residence_upc_input,$this->input->post('price_change'));

获取值然后使用foreach()

答案 2 :(得分:0)

更改所有列:

<div class="column">
    <input type="text" name="start_date[1][]" value="1111">
    <input type="text" name="end_date[1][]" value="1111">
    <input type="text" name="price_change[1][]" value="1111">
</div>
....

为:

<form method="post">
<div class="column">
    <input type="text" name="start_date[]" value="1111">
    <input type="text" name="end_date[]" value="1111">
    <input type="text" name="price_change[]" value="1111">
</div>
....

</form>