问题
I have a simple PHP Array called $categories that looks like this:
Array
(
[Closed] => P1000
[Open] => P1001
[Pending] => P1002
[In Progress] => P1003
[Requires Approval] => P1004
)
I've got a simple HTML form that has a drop down list for one field that I would like to use the array for the options, however I only want it do show the text (e.g. Closed, Open, Pending, In Progress and Requires Approval) as the options in the drop down list but store the associated key for that option (e.g. P1000, P1001 etc) which is then sent as a POST value when the form is submitted.
The HTML for the form field so far is:
<select name="category_id">
<option value=""></option>
<?php foreach($categories as $category) {$category = htmlspecialchars($category);?>
<option value="<?php echo $category; ?>"><?php echo $category; ?></option>
<?php
}
?>
</select>
I can get it to display either the text or the ID's but not the text and store the ID. Hopefully this is something simple that someone can point me in the right direction.
Many thanks, Steve
回答1:
You've forgot about $value tag. You were pasting Category name twice, instead of value. You should do that:
<select name="category_id">
<option value=""></option>
<?php
# !vCHANGEv!
foreach($categories as $category => $value)
{
$category = htmlspecialchars($category);
echo '<option value="'. $value .'">'. $category .'</option>';
}
?>
</select>
回答2:
As you have to include key and value both key is to show the text and value for POST
<?php foreach($categories as $key => $category) {
$category = htmlspecialchars($category);?>
<option value="<?php echo $category; ?>"><?php echo $key; ?></option>
<?php
}
?>
回答3:
you have not included keys in foreach loop
foreach($categories as $id=>$category){
$category = htmlspecialchars($category);
echo "<option value="{$id}">{$category}</option>";
}
回答4:
foreach($categories as $category => $category_id)
Is what you're looking for.
回答5:
<select name="category_id">
<option value=""></option>
<?php
$keys = array_keys($categories);
for($i=0; $i<count($categories); $i++)
{?>
<option value="<?php echo $keys[$i]; ?>"><?php echo $categories[$i]; ?></option>
<?php
}
?>
</select>
Supposing that $categories is the array you have shown above.
来源:https://stackoverflow.com/questions/5652465/php-array-and-html-form-drop-down-list