PHP为下拉菜单按字母顺序对数组进行排序(顶部除ONE值以外) [英] PHP Sort an array alphabetically except ONE value on top, for a dropdown menu

查看:129
本文介绍了PHP为下拉菜单按字母顺序对数组进行排序(顶部除ONE值以外)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试破解一个下拉菜单,以从多个国家/地区中提取信息,以使美国"(编号1)显示在顶部,而其他所有国家/地区则按字母顺序排序.如何使用usort函数对数组进行排序,除美国以外的所有国家都排在最前面?也欢迎任何其他建议.这是代码:

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'); 

推荐答案

带有索引数组

步骤

  1. 在数组中查找资源
  2. 未设置数组变量
  3. 使用array_unshift将资源添加为数组中的第一个元素(array_unshift —在数组的开头添加一个或多个元素- 代码

     if (in_array('yourResource', $a_array)){
        unset($a_array[array_search('yourResource',$a_array)]);
        array_unshift($a_array, 'yourResource');
     }
    

    具有多维数组

    $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;
      }
    }
    

    这篇关于PHP为下拉菜单按字母顺序对数组进行排序(顶部除ONE值以外)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆