使用php嵌套数组列表使用optgroup进行下拉列表

时间:2012-12-14 07:06:21

标签: php arrays optgroup

我有这个嵌套数组,我想将它转换为下拉列表,但在输出时它只显示我的组合框,选项为(数组,数组,数组)

 <select name="pcity" id="pcity" multiple="multiple">

<?php
$pcitylist = array('Andaman and Nicobar' => array('North and Middle Andaman',
    'South Andaman', 'Nicobar'), 'Andhra Pradesh' => array('Adilabad', 'Anantapur',
    'Chittoor', 'East Godavari', 'Guntur', 'Hyderabad', 'Kadapa', 'Karimnagar',
    'Khammam', 'Krishna', 'Kurnool', 'Mahbubnagar', 'Medak', 'Nalgonda', 'Nellore',
    'Nizamabad', 'Prakasam', 'Rangareddi', 'Srikakulam', 'Vishakhapatnam',
    'Vizianagaram', 'Warangal', 'West Godavari'), 'Arunachal Pradesh' => array('Anjaw',
    'Changlang', 'East Kameng', 'Lohit', 'Lower Subansiri', 'Papum Pare', 'Tirap',
    'Dibang Valley', 'Upper Subansiri', 'West Kameng'));
foreach ($pcitylist as $pcitylist1) {
    echo '<option value="' . $pcitylist1 . '"' . (isset($_POST['pcity']) && $_POST['pcity'] ==
        $pcitylist1 ? ' selected' : '') . '>' . $pcitylist1 . '</option>';
}              

 ?>         
 </select>

我希望它像这样显示

<select>
<optgroup>Andaman and Nicobar</optgroup>
<option>North and Middle Andaman</option>
<option>South Andaman</option>.....
</select>

依旧......

2 个答案:

答案 0 :(得分:2)

foreach ($pcitylist as $key => $pcitylist1)
{
      echo '<optgroup label="'.$key.'">';
      foreach ($pcitylist1 as $finalCity) {
          echo '<option value="' . $finalCity . '"' . (isset($_POST['pcity']) && $_POST['pcity'] == $finalCity ? ' selected' : '') . '>' . $finalCity . '</option>';
      }   
      echo '</optgroup>';
} 

$key包含optgroup标签。这将适用于您的阵列。

答案 1 :(得分:1)

这是一个多维数组......在你的循环中再使用一个循环,你将获得输出...

尝试以下方法..

foreach ($pcitylist as $key => $pcitylist1)
{ 
      foreach ($pcitylist1 as $finalCity) {
          echo '<option value="' . $finalCity . '"' . (isset($_POST['pcity']) && $_POST['pcity'] == $finalCity ? ' selected' : '') . '>'.$key . $finalCity . '</option>';
      }    
}