排序具有特殊字符的数组

时间:2015-08-27 15:31:33

标签: php arrays sorting

名称的排序值将首先按字母顺序排列," @"他们之后的名字?

所以排序如下:

 @3
 zpo
 ahb
 @1
 @7
 bes
 kk

像这样:

 ahb
 bes
 kk
 zpo
 @1
 @3
 @7

如果我使用asort()," @"名字是第一个,它们必须是最后的。

4 个答案:

答案 0 :(得分:2)

这是一种有趣的方式:

 asort($array); 
 $array = (array_diff($array, $temp = preg_grep('/^@/', $array)) + $temp);
  1. 使用@
  2. 查找以preg_grep()开头的所有项目
  3. 找出差异,即使用@
  4. array_diff()开头的项目
  5. 添加2 + 1
  6. 如果您想要所有特殊字符,可以尝试使用/^[^\w\d]/或特定字符,例如/^[@%#]/等。

答案 1 :(得分:1)

以下是使用usort

的方法
usort($a,function($a,$b) {
    //if the left string starts with an '@' and
    //and the right string doesn't start with an '@',
    //then the left string is considered greater than the right, return 1        
    if($a[0] == '@' && $b[0] != '@') {
        return 1; 
    }    

    //see above comment        
    if($b[0] == '@' && $a[0] != '@') {
        return -1;
    }

    //if both strings start with an '@'
    //or both strings do not start with an '@'
    //do a regular comparison
    return strcmp($a,$b);
});

答案 2 :(得分:1)

你可以做一个常规的排序,但是把它们放在一个以@开头的值,把它们放在一个单独的数组中并合并它们(第二个数组将被附加到第一个数组)。像这样:

public static Nullable<T> NullIf<T>(T first, T second) where T : struct
{
    if(first == second)
        return new Nullable<T>();
    return new Nullable<T>(first);
}

答案 3 :(得分:0)

另一种方式:

$arr = array(
 '@3',
 'zpo',
 'ahb',
 '@1',
 '@7',
 'bes',
 'kk',
);
function sorting($array){
    asort($array);
    foreach($array as $k=>$v){
        if(strstr($v,'@')){
            unset($array[$k]);
            array_push($array,$v);
        }
    }
    return $array;
}
var_dump(sorting($arr));
相关问题