如何在php中对选择选项进行排序?
现在,它可以按字母顺序对select选项进行排序。但如何将“未指定”作为选中选项?我希望“未指定”位于选项列表的顶部,并对所有其他选项进行排序。我试着用in_数组,但没有成功如何在php中对选择选项进行排序?,php,sorting,options,Php,Sorting,Options,现在,它可以按字母顺序对select选项进行排序。但如何将“未指定”作为选中选项?我希望“未指定”位于选项列表的顶部,并对所有其他选项进行排序。我试着用in_数组,但没有成功 <select name="fav_games" id="fav_games"> <?php $fav_games = array("Battlefield", "Madden", "Need 4 Speed", "World of Warcraft", "Unspeci
<select name="fav_games" id="fav_games">
<?php
$fav_games = array("Battlefield", "Madden", "Need 4 Speed", "World of Warcraft", "Unspecified");
sort($fav_games);
$clength = count($fav_games);
for($x = 0; $x < $clength; $x++) {
echo '<option value="' .$fav_games[$x] . '">' . $fav_games[$x] . '</option>';
}
?>
</select>
一个简单的解决方案:
$fav_games = [....]; //all options except 'Unspecified'
sort($fav_games);
$fav_games = array_merge(['Unspecified'], $fav_games);
受@0x23212f评论的启发,我会这样做。这似乎是我选择的最直接的方式:
sort($fav_games);
array_unshift($arr , 'Unspecified');
应该非常简单-(1)对列表进行排序,不使用“未指定”选项(2)将“未指定”添加到列表顶部:)