我正在尝试编写一个脚本,该脚本可让您使用每个国家/地区的城市生成。城市应该通过PHP数组按国家分组。
所以这里的示例使用HTML,但我想要的是PHP Array。
<select>
<optgroup label="Country X">
<option value="City1">City 1</option>
<option value="City2">City 2</option>
<option value="City3">City 3</option>
<option value="City4">City 4</option>
<option value="City5">City 5</option>
</optgroup>
<optgroup label="Country Y">
<option value="City6">City 6</option>
<option value="City7">City 7</option>
<option value="City8">City 8</option>
<option value="City9">City 9</option>
<option value="City10">City 10</option>
</optgroup>
<optgroup label="Country Z">
<option value="City11">City 11</option>
<option value="City12">City 12</option>
<option value="City13">City 13</option>
<option value="City14">City 14</option>
<option value="City15">City 15</option>
</optgroup>
</select>
以下是我到目前为止使用PHP完成的代码...这个代码的主要问题是每个国家/地区拥有所有城市。我只想要5个城市,分别在不同的国家/地区。
<?php
$countries = array(
'Country X',
'Country Y',
'Country Z',
);
$cities = array(
'City 1',
'City 2',
'City 3',
'City 4',
'City 5',
'City 6',
'City 7',
'City 8',
'City 9',
'City 10',
'City 11',
'City 12',
'City 13',
'City 14',
'City 15',
);
?>
<select name="places">
<?php foreach($countries as $key): ?>
<optgroup label="<?php echo $key; ?>">
<?php foreach($cities as $key => $value): ?>
<?php echo '<option value="'.$key.'">'.$value.'</option>'; ?>
<?php endforeach; ?>
</optgroup>
<?php endforeach; ?>
</select>
答案 0 :(得分:1)
将城市分成几块:
$cities = array_chunk($cities, 5);
$counter = 0;?>
<select name="places">
<?php foreach($countries as $key): ?>
<optgroup label="<?php echo $key; ?>">
<?php foreach($cities[$counter++] as $key => $value): ?>
<?php echo '<option value="'.$key.'">'.$value.'</option>'; ?>
<?php endforeach; ?>
</optgroup>
<?php endforeach; ?>
</select>