2012-12-14 57 views
1

我有這個嵌套數組,並且我想將它轉換爲下拉列表,但是在輸出時,它只是向我顯示帶有選項的組合框(數組,陣列)使用PHP嵌套數組列表使用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> 

等等...

+0

''語法是不正確的。 –

+0

@PankitKapadia你應該給他看正確的語法。 – beerwin

+1

正確的語法是:'' – beerwin

回答

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標籤。這將與你的數組一起工作。

+0

非常感謝,它給了我適當的輸出 – raj

1

它是一個多維數組...使用一個多爲循環內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>'; 
     }  
} 
+0

Thnks您的性反應,你的代碼我只有列表選項,我想列表選項與他們的組名稱,因爲我們得到它使用標記。我想要選項組名稱也來到該列表 – raj

+0

使用此變量內forloop訪問組名稱.. $ pcitylist1 –

+0

因爲我是新來的PHP可以寫你如何使用$ pcitylist1 for循環,所以我可以得到結果 – raj