2012-11-16 52 views
0

我有這樣的代碼:如何將此數組修改爲關聯數組?

$genders = array('Male', 'Female'); 

foreach ($genders as $gender) { 
echo '<option' . ($rowMyBiodata['Gender'] == $gender ? ' selected' : '') . '>'; 
echo $gender; 
echo '</option>'; 
} 

和代碼生成HTML代碼:

<option selected>Male</option> 
<option>Female</option> 

現在,我想在每個選項添加值,使得輸出將是這樣的:

<option selected value='M'>Male</option> 
<option value='F'>Female</option> 

我想通過改變數組關聯數組可以解決這個問題:

$genders = array('M'=>'Male', 'F'=>'Female'); 

但如何獲得數組的索引,因此它可以用作選項標籤上的值?

回答

1

像這樣:

$genders = array('M' => 'Male', 'F' => 'Female'); 

foreach ($genders as $key => $value) { 
    echo '<option' . ($rowMyBiodata['Gender'] == $value ? ' selected' : '') . ' value="' . $key . '">'; 
    echo $value; 
    echo '</option>'; 
} 
+0

它的工作兄弟!非常感謝... –

1

你只需要你的輸出腳本改變這樣的事情:

$genders = array('M' => 'Male', 'F' => 'Female'); 

foreach ($genders as $gender => $description) { 
    echo '<option value='.$gender.' ' . ($rowMyBiodata['Gender'] == $description ? ' selected' : '') . '>'; 
    echo $description; 
    echo '</option>'; 
} 

注意新的使用foreach則params的有$關鍵=> $值對,然後在你的輸出

使用此
0

使用方法如下,

foreach ($genders as $key=>$gender) { 
    echo '<option value='.$key.' . ($rowMyBiodata['Gender'] == $gender ? ' selected' : '') . '>'; 
    echo $gender; 
    echo '</option>'; 

}