简体   繁体   English

PHP-获取在下拉框中选择的选项的索引/关联值

[英]PHP- Get index/associated value of option selected in dropdown box

I want to show values in a dropdown box (either from an array or database - please advise on which option is method) 我想在下拉框中显示值(从数组或数据库中显示-请告知哪个选项是方法)

Then 然后

when a user selects a value in dropdown box, i want to have and get its associated index value (like 1, 2). 当用户在下拉框中选择一个值时,我想拥有并获取其关联的索引值(如1、2)。

For example: dropdown box shows values: 例如:下拉框显示值:

"Car" “汽车”
"Bicycle" “自行车”

If user selects "Car", when i get dropdown selected value, i should get 1, similarly for "Bicycle" i get 2 .. and so on. 如果用户选择“汽车”,则当我得到下拉选择值时,我应该得到1,类似“自行车”,我得到2 ..以此类推。

Please advise easy and simplest method to implement this 请告知实现此目的的最简单方法

Thanks 谢谢

You can use two methods: 您可以使用两种方法:

1) Set up prior to display a code that holds associative array with key -> value ie: 1 => Car (you can keep it in config file if it doesn't change frequently, you can pull it from database or you can keep it in some other form: serialized, file etc.) and use it when the submitted form is being processed. 1)设置之前显示带有键->值的关联数组的代码,即:1 => Car(如果不经常更改,可以将其保存在配置文件中,可以将其从数据库中拉出,也可以保留并以其他形式(序列化,文件等)进行处理,并在处理提交的表单时使用它。

2) Use array with key and value with the same string ie: Car => Car and when the form is processed you will have value right away. 2)使用具有相同字符串和键和值的数组,即:Car => Car,在处理表单时,您将立即获得值。 This solution has some limitations and be troublesome with using more words or other characters that need to be sanitized. 该解决方案具有一些局限性,并且在使用更多需要清理的单词或其他字符时会遇到麻烦。

I would advise option 1, you will have to set up the list before and use it after form has been processed but it allows more freedom and its less maintenance. 我建议选择1,您必须先设置列表,然后在处理表单后再使用它,但是它可以提供更大的自由度和更少的维护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM