使用PHP中的optgroup迭代下拉列表

时间:2013-10-23 22:29:30

标签: php mysql codeigniter optgroup

我正在使用CodeIgniter开发一个应用程序我的下拉列表中包含86个选项,这些选项应该动态生成,我决定在<optgroup>中创建它们,如下面的屏幕截图所示。

enter image description here

我已将所有这些选项存储在mysql数据库中。现在我的问题是我想使用foreach()循环迭代这些选项,以便为每个组显示组标签。 (在屏幕截图Education,Hospitality中)。我不喜欢这些86选项的硬编码方式。有人可以帮助我解决这个问题。

修改

这是我的MySQL表。我提到了教育清单而不是职业清单。但表结构是一样的。

mysql> select * from wededucationlist limit 10;
      +-------+---------------------------+
      | eduid | education                 |
      +-------+---------------------------+
      |     1 | Aeronautical Engineering  |
      |     2 | B Arch                    |
      |     3 | BCA                       |
      |     4 | BE/B-Tech                 |
      |     5 | B Plan                    |
      |     6 | BSc IT / Computer Science |
      |     7 | Other Bachelor Degree     |
      |     8 | M Arch                    |
      |     9 | MCA                       |
      |    10 | ME                        |
      +-------+---------------------------+
      10 rows in set (0.00 sec)

2 个答案:

答案 0 :(得分:1)

即使您提到的表格不包含所需的数据,也有一个实现您想要实现的目标的基本原则:

  • 查询应构成<options>的所有行,并添加第二列,即<optgroup>
像这样:

Option 1 | Group 1
Option 2 | Group 1
Option 3 | Group 2
Option 4 | Group 3
  • 迭代所有选项,每当组发生变化时,打印出一个optgroup:

这一个:

  <?php
    $data = array(array("option" => 1, "group" => "Group 1"),
       array("option" => 2, "group" => "Group 1"), 
       array("option"=>3, "group" => "Group 2"));

    $priorGroup = ""; 
    echo "<select>";
    foreach ($data AS $entry){
      if ($entry["group"] != $priorGroup){ //Start new optgroup if group changed.
         if ($priorGroup != ""){ //close prior optgroup if prior group WAS set.
           echo "</optgroup>"; 
         }

         echo "<optgroup label='{$entry["group"]}'>"; 
      }

      echo "<option>{$entry["option"]}</option>"; //show option(s)
      $priorGroup = $entry["group"]; //update priorGroup.
    }


    echo "</optgroup></select>"; //close last optgroup + select.
?>

将输出:

 Group 1
    1
    2
 Group 2
    3

您的数据库查询需要按组排序(以及之后可选的选项),否则您可能会得到以下内容:

 Group 1
    1
 Group 2
    3
 Group 1
    2

答案 1 :(得分:0)

在codeigniter中具有动态下拉列表的Optgroup可能是这样的:


    //SANI: dropdown with optgroup   
    $result = $this->db->query("SELECT * FROM tbl_classes WHERE cls_id > '".$classId."'");
        $return = array('' => '-- Select Class -- ');
        if($result->num_rows() > 0) 
        {
            foreach($result->result_array() as $row) 
            {
                $resSec = $this->db->query("SELECT * FROM tbl_section WHERE sec_cls_id = '".$classId."'");
                if($resSec->num_rows() > 0) 
                {
                    foreach($resSec->result_array() as $sec)
                    { 
                        $return[$row['cls_name']][$sec['sec_id']] = $sec['sec_name'];
                    }
                }
            }
        }
        return $return;
相关问题