2014-01-16 99 views
0

具有相同的組名的多個記錄,我想在笨從數據庫填充select下拉與optgroup爲我寫了以下內容:顯示笨

表:

+---+-------------+--------------+ 
|id | group_name | location_name| 
+---+-------------+--------------+ 
| 1 | top cities | Bangalore | 
| |    |    | 
| 2 | top cities | Chennai  | 
| |    |    | 
| 3 | big cities | Mumbai  | 
| |    |    | 
| 4 | small cities| mumbai  | 
| |    |    | 
| 5 | small cities| mumbai  | 
+---+-------------+--------------+ 

要求:

  <select id="location" name="location"> 
       <option value="" selected="selected">Select Location</option> 
       <optgroup label="top cities"> 
        <option value="Bangalore">Bangalore</option> 
        <option value="Chennai">Chennai</option> 
       </optgroup> 
       <optgroup label="big cities"> 
        <option value="Mumbai">Mumbai</option> 
       </optgroup> 
       <optgroup label="small cities"> 
        <option value="Mumbai">Mumbai</option> 
        <option value="Mumbai">Mumbai</option> 
       </optgroup> 
      </select> 

型號:

function get_location() { 
    $this->db->select('group_name,GROUP_CONCAT(location_name) AS locations'); 
    $this->db->order_by("group_name"); 
    $this->db->from('location'); 
    $query = $this->db->get(); 
    if ($query->num_rows() > 0) { 
     foreach ($query->result() as $row) { 
      $data[] = $row; 
     } 
     return $data; 
    } 
    return false; 
} 

查看:

  <select id="location" name="location"> 
       <option value="" selected="selected">Select Location</option> 
       <?php 
       $CI = & get_instance(); 
       $CI->load->model('Common', 'Common', TRUE); 
       $results = $CI->Common->get_location(); 
       foreach ($results as $row) { 
        echo '<optgroup label="'.$row->group_name.'">'; 

        $location = explode(',', $row->locations); 
        foreach ($location as $loc) { 
         echo '<option value="'.$loc.'">'.$loc.'</option>'; 
        } 

        echo "</optgroup>"; 
       } 
       ?> 
      </select> 

但結果是不同的,那麼我需要......

輸出:

 <select id="location" name="location"> 
      <option value="" selected="selected">Select Location</option> 
      <optgroup label="top cities"> 
       <option value="Bangalore">Bangalore</option> 
       <option value="Chennai">Chennai</option> 
       <option value="Mumbai">Mumbai</option> 
       <option value="Mumbai">Mumbai</option> 
       <option value="Mumbai">Mumbai</option> 
      </optgroup> 
     </select> 

請幫助任何人...在此先感謝

+0

你能顯示輸出目前是什麼? –

+0

我已經更新了輸出的問題 –

回答

0

這是因爲你的查詢是錯誤的。您應該將以下行添加到您的查詢中:

$this->db->group_by('group_name'); 

另一件事,你不應該從你的視圖訪問你的模型。您應該使用控制器從模型中獲取數據並將其傳遞給視圖。

+0

非常感謝你...先生... –

0

也嘗試不同的

$this->db->distinct(); 

放在什麼地方查詢