具有相同的組名的多個記錄,我想在笨從數據庫填充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>
請幫助任何人...在此先感謝
你能顯示輸出目前是什麼? –
我已經更新了輸出的問題 –