使用SQL查询中的optgroup构建select

时间:2014-05-16 01:46:47

标签: php sql

我有下表:

___标题

| TIT_Id | TIT_en | TIT_Popularity |
| 1      | Sir    | High           |
| 2      | Madam  | High           |
| 2      | Emir   | Low            |

我该如何选择?

<select>
  <optgroup label="High">
    <option value='1'>Sir</option>
    <option value='2'>Madam</option>
  </optgroup>
  <optgroup label="Low">
    <option value='3'>Emir</option>
  </optgroup>
</select>

我试过了:

SELECT TIT_Id, TIT_en FROM ___Titles
GROUP BY TIT_Popularity
ORDER BY TIT_en ASC

感谢。

2 个答案:

答案 0 :(得分:1)

这个怎么样?使用如下查询获取结果:

SELECT * FROM ___Titles ORDER BY TIT_Popularity;

这实际上会根据TIT_Popularity将结果分组。然后你可以像这样迭代它们:

echo "<select>\n";

$currentGroup = null;
foreach( $results as $result ) {
    // start a new optgroup
    if( $currentGroup == null || $result->TIT_Popularity != $currentGroup ) {
        // end the previous group
        if( $currentGroup != null ) {
            echo "</optgroup\n>";
        }

        // start a new group
        echo "<optgroup label='{$result->TIT_Popularity}'>\n";

        $currentGroup = $result->TIT_Popularity;
    }

    echo "<option value='{$result->TIT_Id}'>{$result->TIT_en}</option>\n";
}

// end the last opt group
if( $currentGroup != null ) echo "</optgroup>\n";


echo "</select>\n";

答案 1 :(得分:0)

或者,您可以从选定的数据库中处理数组(因为查询不在问题中),只需构建它们并在新创建的数组上重新排序(如果流行度很高/很低)。考虑这个例子:

<?php

// dummy data, since no values are provided on the question
$values_from_db = array(
    array('TIT_Id' => 3, 'TIT_en' => 'Emir', 'TIT_Popularity' => 'Low'),
    array('TIT_Id' => 4, 'TIT_en' => 'Test', 'TIT_Popularity' => 'Low'),
    array('TIT_Id' => 1, 'TIT_en' => 'Sir', 'TIT_Popularity' => 'High'),
    array('TIT_Id' => 2, 'TIT_en' => 'Madam', 'TIT_Popularity' => 'High'),

);

$sorted_values = array();
foreach($values_from_db as $key => $value) {
    $sorted_values[$value['TIT_Popularity']][] = array(
        'TIT_Id' => $value['TIT_Id'],
        'TIT_en' => $value['TIT_en'],
    );
}

ksort($sorted_values);

?>

<select name="whatever">
    <option selected disabled>Select Value</option>
<?php foreach($sorted_values as $key => $value): ?>
    <optgroup label="<?php echo $key; ?>">
        <?php foreach($value as $index => $element): ?>
            <option value="<?php echo $element['TIT_Id']; ?>"><?php echo $element['TIT_en']; ?></option>
        <?php endforeach; ?>            
    </optgroup>
<?php endforeach; ?>
</select>