简体   繁体   English

如何使用PHP在选择框中选择从多个选项或具有不同值的数组到视图的设置选项

[英]How to set an option from multiple options or array with different values to views as selected in select box using PHP

An option value is taken from the database and included in a select box along with other options. 从数据库中获取一个选项值,并将其与其他选项一起包含在选择框中。 How can I set the value taken from the database as selected? 如何设置从数据库中选取的值?

The value from the database is set as $row['value'] and equals s. 数据库中的值设置为$ row ['value']并等于s。 In HTML the options look like so... 在HTML中,选项看起来像这样...

<select name="select">
<option value='xxs'>Extra, Extra small</option>
<option value='xs'>Extra small</option>
<option value='s'>Small</option>
<option value='m'>Medium</option>
<option value='l'>Large</option>
<option value='xl'>Extra Large</option>
<option value='xxl'>Extra, Extra small</option>
</select>

What I want is the $row['value'] (Small) option to be displayed on page load... Is this possible? 我想要的是$ row ['value'](Small)选项在页面加载时显示...这可能吗?

The good news is, this is possible and in PHP is quite simple really. 好消息是,这是可能的,并且在PHP中确实非常简单。 First we put all of our options and their respective values in an array like so: 首先,我们将所有选项及其各自的值放在一个数组中,如下所示:

<?php
$options=array('Extra, Extra small'=>'xxs','Extra small'=>'xs','Small'=>'s','Medium'=>'m','Large'=>'l','Extra Large'=>'xl','Extra, Extra Large'=>'xxl');

Follow this by opening the select box and calling upon the options array in a foreach loop... 接下来,打开选择框并在foreach循环中调用options数组。

echo '<select>';
foreach($options as $view=>$value){

As you may have noticed the array contains fields that look like 'Large'=>'l' and the for each loop is calling upon the options as $view=>$value. 您可能已经注意到,数组包含看起来像“大” =>“ l”的字段,并且for每个循环都将选项调用为$ view => $ value。 $view represents the name field, in this case 'Large' and $value represents the value field 'l'. $ view表示名称字段,在这种情况下为'Large',而$ value表示值字段'l'。 This is important if you expect the user to see different options in the select box than what the values are set at. 如果您希望用户在选择框中看到与设置值不同的选项,则这很重要。

Next we create the variable $selected which is going to be used to determine if there is a match between $row['value'] and $value... 接下来,我们创建变量$ selected,该变量将用于确定$ row ['value']和$ value之间是否存在匹配项...

$selected=($row['value'] == $value)? "selected" : "";

This is the same as using an if and else statement to set the variable, but shorter. 这与使用if和else语句设置变量相同,但是更短。 The first section after the variable is asking if $row['value'] is equal to $value, if it does then $selected="selected" else (:) $selected is set to blank. 变量后的第一部分询问$ row ['value']是否等于$ value,如果是,则$ selected =“ selected”否则(:) $ selected设置为空白。

Next we include the options. 接下来,我们包括选项。 Because it is in the foreach loop, we only need one line to insert all of the options... 因为它在foreach循环中,所以我们只需要一行就可以插入所有选项...

echo '<option '.$selected.' value="'.$value.'">'.$view.'</option>';

Remember the $selected variable in the last step? 还记得最后一步中的$ selected变量吗? Each time the foreach loop goes through a section of the options array set at the beginning, it checks to see if $row['value'] equals $value. 每当foreach循环遍历开始时设置的options数组的一部分时,它将检查$ row ['value']是否等于$ value。 If it does then $selected will be set as selected and that particular option will be the one that is shown on page load. 如果确实如此,则$ selected将被设置为selected,并且该特定选项将是页面加载中显示的选项。 It continues through the rest of the array until all views and values have been scanned and returns their respective options. 它会继续遍历数组的其余部分,直到扫描完所有视图和值并返回其各自的选项。

Finally we close the foreach loop and the select box... 最后,我们关闭foreach循环和选择框。

}
echo '</select>';

And there you have it, an automatic way to make a select box option set as selected. 有了它,就可以自动将选择框选项设置为选中状态。 A similar pattern can be used for check-boxes, radio selectors, tabs and more. 类似的样式可用于复选框,单选框,选项卡等。

The full code... 完整代码...

<?php
$options=array('Extra, Extra small'=>'xxs','Extra small'=>'xs','Small'=>'s','Medium'=>'m','Large'=>'l','Extra Large'=>'xl','Extra, Extra Large'=>'xxl');

echo '<select>';

foreach($options as $view=>$value){
    $selected=($row['value'] == $value)? "selected" : "";
echo '<option '.$selected.' value="'.$value.'">'.$view.'</option>';
}

echo '</select>';

Given this array, and this value to be the selected value... 给定此数组,并将此值作为选定值...

$options = array(
                 'Extra, Extra small' => 'xxs',
                 'Extra small' => 'xs',
                 'Small' => 's',
                 'Medium' => 'm',
                 'Large' => 'l',
                 'Extra Large' => 'xl',
                 'Extra, Extra Large' => 'xxl'
           );

$selected = 'm';  // $selected can be swapped for $row['value'] as in the OP 

There are several ways to dynamically construct the option tags inside of a <select> and set the selected attribute on one of them. 有几种方法可以在<select>内部动态构造选项标签,并在其中之一上设置selected属性。

First the one-liner inside a foreach loop: 首先在foreach循环中使用单线:

echo "<select name=\"select\">";
    foreach($options as $text=>$value){
        echo "<option value=\"$value\"" , ($selected == $value ? " selected" : "") , ">$text</option>";
    }
echo "</select>";

This code block uses a ternary conditional operator aka conditional operator aka shorthand if/else aka inline conditon . 此代码块使用ternary conditional operator aka conditional operator aka shorthand if/else aka inline conditon Go here for further reading and examples. 请转到此处以获取更多阅读信息和示例。

  • By using double quotes " you avoid having to toggle back and forth between literal strings and variables. *You will have to escape double quotes that are nested inside of the string by prepending \\ . *Variables can be wrapped in curly brackets to isolate their variable name from the surround text. *Single quotes will not echo the value of the variable.) For continued read about quoting: reference 通过使用双引号"您不必在文字字符串和变量之间来回切换。*您将不得不通过在\\前面加上\\来转义嵌套在字符串内的双引号。*变量可以用大括号括起来以分隔变量*用单引号将不反映变量的值。)有关引号的更多信息,请参见

  • By using , (commas) instead of . 通过使用, (逗号)代替. (dots) to concatenate the string, performance is increased. (点)连接字符串,性能得到提高。 one benchmark 一个基准

  • By only adding a space before the selected attribute in the true condition (versus adding the space outside the condition on every iteration), you avoid creating unnecessary spaces inside your tag. 通过仅在true条件中的selected属性之前添加一个空格(而不是在每次迭代中在条件之外添加一个空格),可以避免在标记内部创建不必要的空格。

  • By using an inline condition statement, you avoid unnecessarily declaring a variable into the global scope. 通过使用内联条件语句,可以避免在全局范围内不必要地声明变量。 If you declare the selected string as a variable, as @independent.guru does, it will be declared/overwritten and used only once on every iteration; 如果您将selected字符串声明为变量,就像@ independent.guru一样,它将被声明/覆盖,并且每次迭代仅使用一次; this can only decrease performance. 这只会降低性能。

Each programmer will have their own preferences about "readability", "brevity", "consistency", and "performance" and may elect to construct their html using any mixture of the above techniques. 每个程序员都将对“可读性”,“简洁性”,“一致性”和“性能”有自己的偏好,并且可以选择使用上述技术的任意组合来构造其html。

As a general rule, I don't bother to declare a variable that I will only use once. 通常,我不必费心声明只使用一次的变量。 In my personal preference hierarchy, brevity , consistency , and performance always come before readability . 在我个人的喜好等级结构中, 简洁一致性性能总是先于可读性

Some of the above points may seem like micro-optimizations, but for a canonical question, it is reasonable to include discussion on performance as any of the listed methods may be copy-pasted directly into projects. 以上几点似乎有些微优化,但是对于一个典型的问题,将性能讨论包括在内是合理的,因为任何列出的方法都可以直接复制粘贴到项目中。

If the first code block was too compact, here are two other versions that spread out the method over multiple lines without generating any extra variables: 如果第一个代码块过于紧凑,则可以使用以下两个版本将方法分散在多行上,而不会产生任何额外的变量:

Separated shorthand if/else syntax: 分隔的简写if / else语法:

echo "<select name=\"select\">";
    foreach($options as $text => $value){
        echo "<option value=\"$value\"";
            echo $selected == $value ? " selected" : "";
        echo ">$text</option>";
    }
echo "</select>";

Standard if conditional: 有条件的标准:

echo "<select name=\"select\">";
    foreach($options as $text => $value){
        echo "<option value=\"$value\"";
            if($selected == $value){
                echo " selected";
            }
        echo ">$text</option>";
    }
echo "</select>";

All of the above versions of the same method will create this rendered html: 相同方法的所有上述版本将创建此呈现的html:

When the page is loaded: 页面加载后:

在此处输入图片说明

When the select element is opened: 当选择元素打开时:

在此处输入图片说明

The source code will look like this: 源代码将如下所示:

<select name="select"><option value="xxs">Extra, Extra small</option><option value="xs">Extra small</option><option value="s">Small</option><option value="m" selected>Medium</option><option value="l">Large</option><option value="xl">Extra Large</option><option value="xxl">Extra, Extra Large</option></select>

This is the source code tabbed out for easier reading: 分出了以下源代码,以便于阅读:

<select name="select">
    <option value="xxs">Extra, Extra small</option>
    <option value="xs">Extra small</option>
    <option value="s">Small</option>
    <option value="m" selected>Medium</option>
    <option value="l">Large</option>
    <option value="xl">Extra Large</option>
    <option value="xxl">Extra, Extra Large</option>
</select>

暂无
暂无

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

相关问题 将选择的选项从选择框传递到另一个php文件 - Passing selected option from select box to a different php file jquery / php从jquery的php数组中选择多个选择的选项 - jquery / php select multiple selected options from php array in jquery 如何将复选框列表/单选框列表/选择选项列表中的所有选项与选定的选项一起通过php发送到服务器? - How to send all options from a checkbox list/radio box list/ select option list to server along with the selected one by php? 使用PHP加载带有选定选项的选择框 - load select box with a selected option using php 如何从多个选择选项中获取多个选择的值php codeigniter? - how to get multiple selected values from multiple select options php codeigniter? 如何在php中获取select框的多个选中值? - How to get multiple selected values of select box in php? 如何显示从数据库中选择的值并显示在 php 的多个选择框中 - How to show the selected values from database and show in multiple select box in php 使用选择选项获取多个选择框选项以保持选定状态 - Getting Multiple Select Box Options to Stay Selected Using Chosen Select 如何从多个选择选项中获取所有选择的值? - How to get all selected values from multiple select option? 如何在使用angularjs的select下拉列表中设置从服务器端(php)获取的默认选择选项值 - How to set default selected option value taken from server side (php) in select drop down using angularjs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM