PHP Sort an array alphabetically except ONE value on top, for a dropdown menu

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 18:02:11

The easiest way to do this is to remove the single value, sort and then re-add it:

working example

// 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

  1. Find resource in array
  2. Unset variable in array
  3. 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;
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!