I have the following table:

___Titles

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

How can I have this select ?

<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>

I tried:

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

Thanks.

有帮助吗?

解决方案 2

Alternatively, you could just process the array from the selected db (since the queries are not inside the question), and just build them and reorder them on that newly created array (provided the popularity is just high/low). Consider this example:

<?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>

其他提示

How about this. Fetch your results using a query like this:

SELECT * FROM ___Titles ORDER BY TIT_Popularity;

This will essentially group your results together by their TIT_Popularity. You can then iterate over them like this:

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";
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top