2010-12-02 80 views
0

将一些代码放在一起时有点麻烦......我试图做的是在代码中添加一些代码来检查单选按钮在数据库中进行检查。CodeIgniter - 检查数据库中是否选中单选按钮

我目前拥有的代码从数据库中获取所有角色,使用foreach语句输出它们,但也将结果拆分为2列,这是我现在所拥有的。

<?php 
$i = 0; 
$output = ""; 
foreach($roles as $row){ 
    if($i > 0){ 
     $i = 0; 
    } 
    if($i == 0) { 
     $output .= "<div class='box'>"; 
    } 

    $output .= '<div class="row">'; 
    $output .= ' <input name="_'.$row->key.'" type="radio" id="'.$row->key.'" class="radio" />'; 
    $output .= ' <label for="'.$row->key.'" style="text-transform: lowercase;">'.$row->name.'</label>'; 
    $output .= '</div>'; 

    if($i ==0) { 
     $output .= "</div>"; 
    } 

    $i++; 
} 
if($i != 1) { 
    $output .= "</div>"; 
} 
echo $output; 

?>

好了,我想要做的是检查代码的单选按钮,我贴了,只有当数据库匹配,所以要得到那名值由用户检查,我使用以下内容。

型号

function get_roles_by_id($freelancerid) 
{ 
    $query = $this->db->query('SELECT * FROM '.$this->table_name.' WHERE user_id = "'.$freelancerid.'"'); 
    return $query->result(); 
} 

然后我的控制器看起来像这样

$data['positions'] = $this->freelancer_roles->get_roles_by_id($freelancer_id); 

由于这是带回一个数组我不能使用foreach语句来检查在该位置返回单选按钮的id阵列。

有人能帮我弄清楚这一点。

干杯,

+0

什么$数据包含位置和角色也是对的? – 2010-12-02 08:43:33

回答

0

我想我明白你的问题,看来你是想做一个相当简单的事情。如果

你应该让你的模型只返回用户保存的复选框的名称数组,格式如下:array(“checkbox1”,“checkbox2”,“checkbox3”)然后在你的输出 你可以简单地使用本地的PHP函数in_array()

例如:

$output .= '<div class="row">'; 
    $output .= ' <input name="_'.$row->key.'" type="radio" id="'.$row->key.'" class="radio"'; 
    if(in_array($row->name, $data['positions']) { $output .= ' checked '; } 
    $output . = '/>'; 
    $output .= ' <label for="'.$row->key.'" style="text-transform: lowercase;">'.$row->name.'</label>'; 
    $output .= '</div>'; 

作为一个侧面说明,你有下面的代码:

if($i > 0){ 
     $i = 0; 
    } 
    if($i == 0) { 
     $output .= "<div class='box'>"; 
    } 

如果您遵循该代码中的逻辑,您将看到$ if将会在第二个if语句中始终等于0,从而使两个if语句成为冗余。

相关问题