0

我有一个需要重新排序的数组。它是一系列国家/地区代码:

$countries = array('uk', 'fr', 'es', 'de', 'it');

我需要首先使用特定用户选择的国家/地区对数组进行排序,即。'fr' 和其余项目需要按字母顺序排列。

我不太确定如何做到这一点,任何帮助将不胜感激。

4

3 回答 3

3
$countries = array('uk', 'fr', 'es', 'de', 'it');
// find and remove user value
$uservar = 'uk';
$userkey = array_search($uservar, $countries);
unset($countries[$userkey]);
// sort ascending
sort($countries,SORT_ASC);
// preappend user value
array_unshift($countries, $uservar);
于 2012-04-30T10:44:30.250 回答
2

这有点长,但应该可以。

<?php
   $user_selected = 'fr';

   $countries = array('uk', 'fr', 'es', 'de', 'it');
   unset($countries[ array_search($user_selected, $countries) ]); // remove user selected from the list
   sort($countries); // sort the rest

   array_unshift($countries, $user_selected); // put the user selected at the beginning

   print_r($countries);
?>
于 2012-04-30T10:45:07.810 回答
0
// The option the user selected
$userSelectedOption = 'fr';

// Remove the user selected option from the array
array_splice($countryCodes, array_search($userSelectedOption, $countryCodes), 1);

// Sort the remaining items
sort($countryCodes, SORT_ASC);

// Add the user selected option back to the beginning
array_unshift($countryCodes, $userSelectedOption);
于 2012-04-30T10:43:48.960 回答