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

我正在处理如何从关联数组输出选定的选项。我使用 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;

}

?>


呼唤远方
浏览 87回答 1
1回答

宝慕林4294392

在代码中添加了带有注释的详细信息。<?php&nbsp; &nbsp; $rateFrom = ['Euro' => 25.62, 'USD' => 22.74, 'GBP' => 28.50, 'AUS' => 15.90, 'CHN' => 3.30];&nbsp; &nbsp; ?>&nbsp; &nbsp; &nbsp;<form action="" method='POST'>&nbsp; &nbsp; &nbsp;<input type="number" name='from'&nbsp; step=any&nbsp; min='1' placeholder='How many euros are you exchanging?' required>&nbsp;&nbsp;&nbsp; &nbsp; <!-- create a input hidden field call currency_name-->&nbsp; &nbsp; &nbsp;<input type="hidden" id="currency_name" name="currency_name">&nbsp; &nbsp; &nbsp;<!-- create a input hidden field. on change the value, get the select option currency name and add into 'currency_name' field.-->&nbsp; &nbsp; <select name="rate" onChange="document.getElementById('currency_name').value = this.options[this.options.selectedIndex].text;">&nbsp; &nbsp; <?php&nbsp; &nbsp; foreach($rateFrom as $key => $value):&nbsp; &nbsp; //use&nbsp; value attr&nbsp; &nbsp; echo '<option value='. $value.'>'. $key.'</option>';&nbsp;&nbsp; &nbsp; endforeach;&nbsp; &nbsp; ?>&nbsp; &nbsp; </select>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; <input type="submit" name='submit'>&nbsp; &nbsp; </form>&nbsp; &nbsp; <?php&nbsp; &nbsp; if(isset($_POST['submit'])){&nbsp; &nbsp; $rate = $_POST['rate'];&nbsp; &nbsp; $from = $_POST['from'];&nbsp; &nbsp; //get the currency name by key 'currency_name'&nbsp; &nbsp; $curency = $_POST['currency_name'];&nbsp; &nbsp; echo 'Your amount'.$from . ' ' .$curency;&nbsp; &nbsp; $to = $from * $rate;&nbsp; &nbsp; }&nbsp; &nbsp; ?>
打开App,查看更多内容
随时随地看视频慕课网APP