Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在php中对选择选项进行排序?_Php_Sorting_Options - Fatal编程技术网

如何在php中对选择选项进行排序?

如何在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选项进行排序。但如何将“未指定”作为选中选项?我希望“未指定”位于选项列表的顶部,并对所有其他选项进行排序。我试着用in_数组,但没有成功

<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)将“未指定”添加到列表顶部:)