Select Dropdown PHP foreach loop with 'optgroup' options

前端 未结 4 518
名媛妹妹
名媛妹妹 2020-12-20 04:10

I have a dropdown menu with a PHP \'foreach\' that I loop through to populate the select options. This works well. However, what I\'d like to do is have various sub labels u

4条回答
  •  借酒劲吻你
    2020-12-20 04:49

    Check if the type changed from the previous value, and then emit the appropriate tags.

    Order the query by type:

    $query = mysql_query("SELECT * FROM background_albums order by type"); //ordered query
    
    [...]
    
    $type = null;
    
    foreach ($albums as $album) {
      if ($album['type'] != $type) {  // type changed
        if ($type !== null) {
          echo '';  // close previous optgroup
        }
        $type = $album['type'];
        echo '';  // start optgroup
      }
    
      [...]
    }
    
    echo '';  // close last optgroup
    

提交回复
热议问题