有没有一种更有效的方法来编写在php中按状态分组的选择列表

时间:2018-04-10 13:27:19

标签: php database select drop-down-menu

我正在建立一个网站,它有一个按州分组的选择列表。有没有更有效的方法来编写这个选择列表,所以我没有写这么多不同的循环?

我的数据库中有一个名为location的表:

id    region            state
1     Sydney            NSW
2     Newcastle         NSW
3     Wollongong        NSW
4     Wagga Wagga       NSW
5     Geelong           Vic

...等

目前我正在按照这样的状态分组的选择列表中打印出来。

<select name="location" id="location">
    <?php 
        $locations = getTable("location", $DB); 
        $locationsByState = [];
        //chunk array by state
        foreach($locations as $loc)
        {
            $locationsByState[$loc['state']][] = $loc;
        }
    ?>
    <optgroup label="NSW">
        <?php
            foreach($locationsByState['NSW'] as $opt)
            echo '<option>' . $opt['region'] .'</option>'
        ?>
    </optgroup>
    <optgroup label="QLD">
        <?php
            foreach($locationsByState['QLD'] as $opt)
            echo '<option>' . $opt['region'] .'</option>'
        ?>
    </optgroup>
    <optgroup label="SA">
        <?php
            foreach($locationsByState['SA'] as $opt)
            echo '<option>' . $opt['region'] .'</option>'
        ?>
    </optgroup>
    <optgroup label="VIC">
        <?php
            foreach($locationsByState['VIC'] as $opt)
            echo '<option>' . $opt['region'] .'</option>'
        ?>
    </optgroup>
    <optgroup label="TAS">
        <?php
            foreach($locationsByState['TAS'] as $opt)
            echo '<option>' . $opt['region'] .'</option>'
        ?>
    </optgroup>
    <optgroup label="WA">
        <?php
            foreach($locationsByState['WA'] as $opt)
            echo '<option>' . $opt['region'] .'</option>'
        ?>
    </optgroup>
    <optgroup label="ACT">
        <?php
            foreach($locationsByState['ACT'] as $opt)
            echo '<option>' . $opt['region'] .'</option>'
        ?>
    </optgroup>
    <optgroup label="NT">
        <?php
            foreach($locationsByState['NT'] as $opt)
            echo '<option>' . $opt['region'] .'</option>'
        ?>
    </optgroup>
</select>

1 个答案:

答案 0 :(得分:2)

您可以通过以下2个简单循环覆盖它:

RewriteRule ^(www.)?/mysite.com/specialpage mysite.com/?specialpage [L,NC,QSA]
RewriteRule ^(www.)?/mysite.com/veryspecialpage mysite.com/?veryspecialpage [L,NC,QSA]