Html 表单/php:选择选项值=数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8457792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Html Form / php : select with option value = array
提问by prestarocket
How can I use a php array as the value of an HTML <option>
?
如何使用 php 数组作为 HTML 的值<option>
?
e.g.
例如
<select name='myname'>
<option value=' array("font-family" => "font-family: 'Yeseva One', serif","font-name" => "Yeseva One","css-name" =>"Yeseva+One")'>
Font 1
</option>
...
</select>
回答by Kristian Hildebrandt
It kind of depends on what you want to archive in the end. I've got 3 options for you:
这有点取决于您最终要存档的内容。我有 3 个选项供您选择:
1) Json is pretty flexible:
1) Json 非常灵活:
<option value="<?php json_encode($yourArray) ?>">Font 1</option
You can then later on convert Json back to an array with json_decode.
然后,您可以稍后使用 json_decode 将 Json 转换回数组。
2) If you need the data for server client side scripting, it would probably be a better idea to use HTML5's data attributes:
2) 如果您需要服务器客户端脚本的数据,使用 HTML5 的数据属性可能是一个更好的主意:
<option value="value1" data-fontname="Yeseva One" data-cssname="Yeseva+One">Font 1</option>
3) You can use hidden input fields, which will allow you to retrieve the values like $_POST['font1']['css_name'] ect. :
3)您可以使用隐藏的输入字段,这将允许您检索 $_POST['font1']['css_name'] 等值。:
<input type="hidden" name="font1[font_name]" value="Yeseva One" />
You will obviously have to escape your values. But you get the idea.
显然,您将不得不逃避您的价值观。但是你明白了。
回答by Galled
I think you can serializethe array:
我认为您可以序列化数组:
<?php
$arrYourArray = array(
"font-family" => "font-family: 'Yeseva One', serif",
"font-name" => "Yeseva One",
"css-name" =>"Yeseva+One");
?>
<select name="myname">
<option value="<?php echo serialize($arrYourArray); ?> ">
Font 1
</option>
...
</select>
回答by Yazan Malkawi
I think the best approach for you is to put the values with comma separation i.e
我认为对你来说最好的方法是用逗号分隔值,即
<select name='myname'>
<option value='Yeseva One, serif'</option>
</select>
and in the php you can implode the result into an array
在 php 中,您可以将结果内爆到一个数组中
$array_of_results = implode( $_POST['myname'] );
回答by Josh Foskett
Are you trying to create a select form based on the options you have set in your array?
您是否正在尝试根据您在数组中设置的选项创建一个选择表单?
If so, you could do this:
如果是这样,你可以这样做:
<select name="myname">
<?php
$selects = Array('Verdana' => 'font-family: Verdana;', '\'Trebuchet MS\', Helvetica, Arial, sans-serif' => 'font-family: \'Trebuchet MS\', Helvetica, Arial, sans-serif;');
foreach($selects as $select => $css) {
echo '<option value="' . $css . '">' . $select . '</option>';
}
?>
</select>