以下函数(类似于上面的函数)将把数组渲染为一系列 HTML select 选项(即 "<option>...</option>")。之前函数的问题是无法处理 <optgroup>,所以这个函数解决了这个问题。
function arrayToSelect($option, $selected = '', $optgroup = NULL)
{
$returnStatement = '';
if ($selected == '') {
$returnStatement .= '<option value="" selected="selected">Select one...</option>';
}
if (isset($optgroup)) {
foreach ($optgroup as $optgroupKey => $optgroupValue) {
$returnStatement .= '<optgroup label="' . $optgroupValue . '">';
foreach ($option[$optgroupKey] as $optionKey => $optionValue) {
if ($optionKey == $selected) {
$returnStatement .= '<option selected="selected" value="' . $optionKey . '">' . $optionValue . '</option>';
} else {
$returnStatement .= '<option value="' . $optionKey . '">' . $optionValue . '</option>';
}
}
$returnStatement .= '</optgroup>';
}
} else {
foreach ($option as $key => $value) {
if ($key == $selected) {
$returnStatement .= '<option selected="selected" value="' . $key . '">' . $value . '</option>';
} else {
$returnStatement .= '<option value="' . $key . '">' . $value . '</option>';
}
}
}
return $returnStatement;
}
例如,我需要在 select 字段中渲染各个国家/地区的州/省列表,并且我想使用每个国家/地区名称作为 <optgroup> 标签。因此,使用此函数,如果只向函数传递单个数组(即 "arrayToSelect($stateList)"),则它将简单地输出一堆 "<option>" 元素。另一方面,如果向它传递两个数组,则第二个数组将成为第一个数组的 "键" 用于翻译。
以下是一个更进一步的示例
$countryList = array(
'CA' => 'Canada',
'US' => 'United States');
$stateList['CA'] = array(
'AB' => 'Alberta',
'BC' => 'British Columbia',
'AB' => 'Alberta',
'BC' => 'British Columbia',
'MB' => 'Manitoba',
'NB' => 'New Brunswick',
'NL' => 'Newfoundland/Labrador',
'NS' => 'Nova Scotia',
'NT' => 'Northwest Territories',
'NU' => 'Nunavut',
'ON' => 'Ontario',
'PE' => 'Prince Edward Island',
'QC' => 'Quebec',
'SK' => 'Saskatchewan',
'YT' => 'Yukon');
$stateList['US'] = array(
'AL' => 'Alabama',
'AK' => 'Alaska',
'AZ' => 'Arizona',
'AR' => 'Arkansas',
'CA' => 'California',
'CO' => 'Colorado',
'CT' => 'Connecticut',
'DE' => 'Delaware',
'DC' => 'District of Columbia',
'FL' => 'Florida',
'GA' => 'Georgia',
'HI' => 'Hawaii',
'ID' => 'Idaho',
'IL' => 'Illinois',
'IN' => 'Indiana',
'IA' => 'Iowa',
'KS' => 'Kansas',
'KY' => 'Kentucky',
'LA' => 'Louisiana',
'ME' => 'Maine',
'MD' => 'Maryland',
'MA' => 'Massachusetts',
'MI' => 'Michigan',
'MN' => 'Minnesota',
'MS' => 'Mississippi',
'MO' => 'Missouri',
'MT' => 'Montana',
'NE' => 'Nebraska',
'NV' => 'Nevada',
'NH' => 'New Hampshire',
'NJ' => 'New Jersey',
'NM' => 'New Mexico',
'NY' => 'New York',
'NC' => 'North Carolina',
'ND' => 'North Dakota',
'OH' => 'Ohio',
'OK' => 'Oklahoma',
'OR' => 'Oregon',
'PA' => 'Pennsylvania',
'RI' => 'Rhode Island',
'SC' => 'South Carolina',
'SD' => 'South Dakota',
'TN' => 'Tennessee',
'TX' => 'Texas',
'UT' => 'Utah',
'VT' => 'Vermont',
'VA' => 'Virginia',
'WA' => 'Washington',
'WV' => 'West Virginia',
'WI' => 'Wisconsin',
'WY' => 'Wyoming');
...
<select name="state" id="state"><?php echo arrayToSelect($stateList,'',$countryList) ?></select>
<select name="country" id="country"><?php echo arrayToSelect($countryList,'US') ?></select>