invalid为控制器中的foreach()提供的无效参数

时间:2017-08-18 04:37:40

标签: codeigniter

我遇到了为foreach()提供的无效参数的问题; 所以我的控制器:

public function insertsebab(){


    foreach($this->input->post('id_konsultasi') as $se) 
    {

        $data = array(
        'id_konsultasi'     =>$se,
        'kd_sebab'      => $this->input->post('kd_sebab')  
             );

        $konsultasi = $this->class_model->insertsebab($data);
        $json =$konsultasi;

        echo json_encode($json);

    }

}

代码错误,如何解决?

2 个答案:

答案 0 :(得分:0)

试试这个

public function insertsebab()
{

    if (is_array($this->input->post('id_konsultasi')) || is_object($this->input->post('id_konsultasi'))) {
        foreach ($this->input->post('id_konsultasi') as $se) {

            $data = array(
                'id_konsultasi' => $se,
                'kd_sebab' => $this->input->post('kd_sebab')
            );

            $konsultasi = $this->class_model->insertsebab($data);
            $json = $konsultasi;

            echo json_encode($json);

        }
    }else{
        //do something if condition is not satisfied or null data
    }
}

我所做的是检查你的$this->input->post('id_konsultasi')是否是数组或对象,所以当$this->input->post('id_konsultasi')为空时它不会返回任何错误

答案 1 :(得分:0)

首先你需要在一个变量中分配后期数据,然后你需要检查它是一个数组而不是空

public function insertsebab()
{
    $kd_sebab = $this->input->post('kd_sebab');
    $var = $this->input->post('id_konsultasi');
    if (is_array($var) &&  !empty($var) {
        foreach ($var as $se) {

            $data = array(
                'id_konsultasi' => $se,
                'kd_sebab' => $kd_sebab
            );

            $konsultasi = $this->class_model->insertsebab($data);
            $json = $konsultasi;

            echo json_encode($json);

        }
    }else{
        //do something if condition is not satisfied or null data
    }
}