根据字符串排序数组?

时间:2012-04-30 10:38:59

标签: php arrays

我有一个我需要重新订购的数组。这是一系列国家/地区代码:

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

我需要首先使用特定用户选择的国家对数组进行排序,即。 'fr'和剩余的项目需要按照alpabetical的顺序。

我不太清楚如何做到这一点,任何帮助都会受到赞赏。

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);
?>

答案 2 :(得分: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);