I am trying to hack a dropdown menu pulling info from an array of countries so that 'United States' (id 1) appears on the top, while every other country is sorted by alphabetical order. How do I sort all EXCEPT United States to remain on top, using usort function for an array? Any alternative suggestions are also welcome. Here is the code:
while (list($key, $value) = each($countries->countries)) {
$countries_array[] = array('id' => $key, 'text' => $value['countryname']);
}
function text_cmp($a, $b) {
return strcmp($a["text"], $b["text"]);
}
usort($countries_array, 'text_cmp');
The easiest way to do this is to remove the single value, sort and then re-add it:
// your countries array goes here:
$countries = array(2=>"Burma", 4=>"Zimbabwe", 10=>"France", 1=>"United States", 13=>"Russia");
$AmericaFKYeah = array(1=>"United States");
$countries =array_diff($countries, $AmericaFKYeah);
asort($countries);
// using + instead of array_unshift() preserves numerical keys!
$countries= $AmericaFKYeah + $countries;
gives you:
array(5) {
[1]=>
string(13) "United States"
[2]=>
string(5) "Burma"
[10]=>
string(6) "France"
[13]=>
string(6) "Russia"
[4]=>
string(8) "Zimbabwe"
}
With Indexed Array
Steps
- Find resource in array
- Unset variable in array
- Add resource as the first element in array with array_unshift (array_unshift — Prepend one or more elements to the beginning of an array - http://php.net/manual/en/function.array-unshift.php)
Code
if (in_array('yourResource', $a_array)){
unset($a_array[array_search('yourResource',$a_array)]);
array_unshift($a_array, 'yourResource');
}
With MultiDimensional Arrays
$yourResorceToFind = 'yourResource';
foreach ($a_arrays as $a_sub_array){
if (in_array($yourResorceToFind, $a_sub_array)){
unset($a_arrays[array_search($yourResorceToFind,$a_sub_array)]);
array_unshift($a_arrays, $a_sub_array);
break;
}
}
来源:https://stackoverflow.com/questions/22791371/php-sort-an-array-alphabetically-except-one-value-on-top-for-a-dropdown-menu