简体   繁体   English

预填充数组中的选择标签

[英]Pre-filling select tags from array

I've got this array: 我有这个数组:

$profession_type = array(
   'Professional Engineers',
   'Accountants',
   'Insurance Professionals',
   'Attorneys',
   'Certified Hazardous Materials Managers',
   'Safety Professional',
   'Industrial Hygienists',
   'IT Professionals',
   'Human Resource'
);

I am display the contents of the array as the options for the select tag: 我将数组的内容显示为select标记的选项:

                        <select name="profession_type[]">
                            <option value=""></option>
EOL;
    foreach ($profession_type as $p){
        print "<option value='" . $p . "'>" . $p . "</option>";
    }
print <<<EOL
                        </select>

I've never pre-filled a drop down box with dynamic values. 我从未用动态值预填充下拉框。 The values in $profession_type will change frequently (and will eventually be driven from a table in the db), so I can't do hard code it. $profession_type的值将频繁更改(最终将由db中的表驱动),因此我无法对其进行硬编码。

EDIT: Sorry my question was unclear. 编辑:对不起,我的问题尚不清楚。

  • The user will select a value from a previous screen (say it's called id) and hit submit. 用户将从上一个屏幕中选择一个值(例如,称为ID),然后点击“提交”。
  • Before the HTML is rendered to the screen, PHP makes a stored procedure call based on the id they selected. 在将HTML呈现到屏幕上之前,PHP根据它们选择的id进行存储过程调用。
  • The values that the stored procedures returns will prefill the "profession_type[]" form field. 存储过程返回的值将预填充“ profession_type []”表单字段。
  • I would like the <option value='accountants' selected>Accountants</option> if the stored procedure returns "Accountants" for the value of "profession_type" based on the id. 如果存储过程基于id返回“ profession_type”的值的“ Accountants”,我希望<option value='accountants' selected>Accountants</option>

Is that more clear? 这更清楚吗? Sorry. 抱歉。

Any suggestions? 有什么建议么?

How about this: 这个怎么样:

print '<select name="profession_type">';
print '<option value=""></option>';
foreach ($profession_type as $p)
{
    if ($p == $chosen_profession)
        print "<option value='" . $p . "' selected='selected'>" . $p . "</option>";
    else
        print "<option value='" . $p . "'>" . $p . "</option>";
}
print '</select>';

This goes in your .php file: 这放在您的.php文件中:

<!-- some HTML here -->

<?php
$profession_type = [result_from_database_query] ?>

<!-- more HTML here -->

<select name="profession_type">
<?php
   foreach ($profession_type as $p){
        print "<option value='" . $p . "'>" . $p . "</option>";
    }
?>
</select>

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

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