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

时间:2019-07-13 13:47:27

标签: 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;
}
?>

1 个答案:

答案 0 :(得分:2)

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

<?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;
    }
    ?>