简体   繁体   中英

foreach() in Model Codeigniter

Good Day All!

I am wondering why is that the foreach() argument not working in this code:

if ($this->db->trans_status() === TRUE) {
    $data = $this->input->post('pTableData');
    $tableData = json_decode($data);

    if (isset($tableData)) {
        foreach ($tableData as $get) {
            $this->insert_activity($id, $get);
        }
    } else {
        echo "NULL";
    }
}

I just to know if var $tableData isset or has value it will proceed to the another function inside the model .

Try this:

if ($this->db->trans_status() === TRUE)
    {
        $data = $this->input->post('pTableData');
        $tableData = json_decode($data, true); // add a second argument as true to force json_decode to parse it to array
        if (isset($tableData) && is_array($tableData)) // check if the $tableData received is actually an array
            {
                foreach ($tableData as $get) 
                    {
                        $this->insert_activity($id, $get);
                    }
            }
                else
                    {
                        echo "NULL";
                    }
            }

Try this:

if (isset($tableData) && is_array( $tableData ) && count( $tableData ) > 0 ){ //is array and has elements
    //your process here with the array
}else{
    // here you proceed to another function like you asked
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM