在codeigniter上显示数组数据复选框

时间:2018-05-22 08:17:39

标签: php codeigniter-3

我有如下表格数据,我想根据其值在复选框中显示数据,数据采用数组的形式,我很难应用它。所以如果数据不存在那么就错了。

   | ID  | choice | 
   | ____|________|
   |  1  |    A   |
   |  1  |    B   |
   |  3  |    C   | 
   |  6  |    A   | 
   |  6  |    C   |
   |  5  |    A   |
   |  5  |    B   |
   |  5  |    C   |

 <input type="checkbox" name="choice[]" value="A"  <?php ($edit[0]['is'] == "A") ? print "checked": ''; ?> >
 <input type="checkbox" name="choice[]" value="B" <?php ($edit[1]['is'] == "A") ? print "checked": ''; ?> >
 <input type="checkbox" name="choice[]" value="C" <?php ($edit[2]['is'] == "A") ? print "checked": ''; ?>>

控制器

public function edit($id) {
    $data = array('edit' => $this->My_models->edit_data($id));
    $this->load->view('template', $data);
}   

模特

function edit_data($id){
    $query = $this->db->select('choice')
                      ->from('my_table')
                      ->where('id', $id)
                      ->get();
    if ($query->num_rows() > 0) {
        foreach ($query->result_array() as $data) {
            $result[] = $data;
        }
        return $result;
    }                         
}   
当我选择的数据只有2或1

时发生

错误

2 个答案:

答案 0 :(得分:0)

在检查子键之前检查父键是否存在。

 <input type="checkbox" name="choice[]" value="A"  <?php (array_key_exists(0, $edit) && $edit[0]['is'] == "A") ? print "checked": ''; ?>>
 <input type="checkbox" name="choice[]" value="B" <?php (array_key_exists(1, $edit) && $edit[1]['is'] == "A") ? print "checked": ''; ?>>
 <input type="checkbox" name="choice[]" value="C" <?php (array_key_exists(2, $edit) && $edit[2]['is'] == "A") ? print "checked": ''; ?>>

答案 1 :(得分:0)

我认为你应该使用php的JdbcTemplate功能

in_array()