making dropdown with optgroup using php nested array list

寵の児 提交于 2020-01-05 05:47:08

问题


I have this nested array and i want to convert it into dropdown ,but at output it is just showing me combo-box with options as (array ,array,array)

 <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>

i want it to display like this

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

and so on...


回答1:


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>';
} 

The $key holds the optgroup label. This will work with your array.




回答2:


It is an multidimensional array... use one more for loop inside ur for loop and u will get the ouput..

Try the following..

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


来源:https://stackoverflow.com/questions/13874186/making-dropdown-with-optgroup-using-php-nested-array-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!