在一个下拉列表中为选项值和文本加载两个数组

时间:2014-11-15 17:54:38

标签: php arrays

请告诉我如何在一个下拉列表中加载两个数组(一个用于值( $ values ),另一个数组( $ colors )用于加载文本

<?php 
$colors = array("Red", "Green", "Blue", "Tellow"); 
$values = array("#444444", "#ff0055", "#bb0055", "#bb4455");

?> 

<select name="color-list">
<?php 
    foreach($colors as $colorslist) 
    {
       echo '<option value="">'.$colorslist.'</option>';
    }
?>
</select>

由于

4 个答案:

答案 0 :(得分:2)

尝试这个简单的逻辑:

<?php 

$colors = array("Red", "Green", "Blue", "Tellow"); 
$values = array("#444444", "#ff0055", "#bb0055", "#bb4455");

?> 

<select name="color-list">

<?php 
    foreach($colors as $key => $color) 
    {
       echo '<option value="'.$color.'">'.$values[$key].'</option>';
    }
?>

</select>

答案 1 :(得分:1)

Combine两个数组然后循环它

$colors = array("Red", "Green", "Blue", "Tellow"); 
$values = array("#444444", "#ff0055", "#bb0055", "#bb4455");
$combined = array_combine($values, $colors);

<select name="color-list">
<?php 
    foreach($combined as $key=>$value) 
    {
       echo '<option value="'.$key.'">'.$value.'</option>';
    }
?>
</select>

答案 2 :(得分:0)

foreach($colors as $idx => $colorslist)
{
    echo '<option value="' . $values[$idx] . '">'.$colorslist.'</option>';
}

您可以通过当前元素$ colors array

的索引从$ values数组访问数据

答案 3 :(得分:0)

为什么不将两个数组合并为一个键和值

$color-list = array("Red"=>"#444444", "Green"=>"#ff0055");
foreach($color-list as $k => $v){
echo "<option value='{$k}'>" . $v . "</option>";

}