使用PHP嵌套数组列表使得下拉与OPTGROUP(making dropdown with optg

2019-10-17 12:24发布

我有这样的嵌套数组,我想将其转换成下拉列表中,但在输出它只是带我的组合框中的选项为(数组,数组,数组)

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

等等...

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

$key保存OPTGROUP标签。 这将与你的阵列的工作。



Answer 2:

这是一个多维数组...使用一个多为循环内UR for循环和U将得到的输出中..

请尝试以下..

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


文章来源: making dropdown with optgroup using php nested array list