如何从所选选项输出值作为关联数组中的键

  • 本文关键字:关联 数组 输出 选项 php
  • 更新时间 :
  • 英文 :


我正在处理如何从关联数组输出选定的选项。我使用 foreach 循环来获取选项列表中的所有数组键,但我需要值来计算输出速率。

我应该如何显示我现在拥有的密钥,但要计算速率,我需要密钥。

提前感谢您的任何帮助南锡

<?php
$rate = ['Euro' => 25.62, 'USD' => 22.74, 'GBP' => 28.50, 'AUS' => 15.90, 'CHN' => 3.30];
?>
html:       
 <form action="" method='POST'>
 <input type="number" name='from'  step=any  min='1' placeholder='How many euros are you exchanging?' required>  
<select name="rate">
<?php
foreach($rateFrom as $key => $value):
echo '<option type= "number" name='. $value.'>'. $key.'</option>'; 
endforeach;
?>
</select>          
<input type="submit" name='submit'>
</form>
<?php
if(isset($_POST['submit'])){
$rate = $_POST['rate'];
$from = $_POST['from'];
$to = $from * $rate;
}
?>

添加了带有代码注释的详细信息。

<?php
    $rateFrom = ['Euro' => 25.62, 'USD' => 22.74, 'GBP' => 28.50, 'AUS' => 15.90, 'CHN' => 3.30];
    ?>

     <form action="" method='POST'>
     <input type="number" name='from'  step=any  min='1' placeholder='How many euros are you exchanging?' required>  
    <!-- create a input hidden field call currency_name-->
     <input type="hidden" id="currency_name" name="currency_name">
     <!-- create a input hidden field. on change the value, get the select option currency name and add into 'currency_name' field.-->
    <select name="rate" onChange="document.getElementById('currency_name').value = this.options[this.options.selectedIndex].text;">
    <?php
    foreach($rateFrom as $key => $value):
    //use  value attr
    echo '<option value='. $value.'>'. $key.'</option>'; 
    endforeach;
    ?>
    </select>          
    <input type="submit" name='submit'>
    </form>
    <?php
    if(isset($_POST['submit'])){
    $rate = $_POST['rate'];
    $from = $_POST['from'];
    //get the currency name by key 'currency_name'
    $curency = $_POST['currency_name'];
    echo 'Your amount'.$from . ' ' .$curency;
    $to = $from * $rate;
    }
    ?>

最新更新