如何使用 PHP 对数组进行排序,忽略 (先生、夫人) 或 一些文章.


How to sort an array with PHP, ignoring the (Mr, Mrs) or Some articles

使用 name 对数组进行排序我有一个数组。

 array(0 => Mr. Bala ,1 => Mr. Santhosh, 2 => Mrs. Camel,3 => Mrs. Vinoth); 

仅根据名称按升序排序

我的预期输出是

array(
  0 => Mr. Bala,
  1 => Mrs. Camel,
  2 => Mr. Santhosh,
  3 => Mr. Vinoth,
);

使用 usort,取字符串的第二部分,按点分割,后面有空格

usort($a, function($i1, $i2) {
        return strcmp(explode('. ',$i1)[1], explode('. ',$i2)[1]);
      });

UPD由于巴特弗里德里希的评论

usort($a, function($i1, $i2) {
            $t = explode('. ',$i1);
            $i1 = (! isset($t[1]) ? $i1 : $t[1]);
            $t = explode('. ',$i2);
            $i2 = (! isset($t[1]) ? $i2 : $t[1]);
            return strcmp($i1, $i2);
          });

演示

UPD2 使其不区分大小写

usort($a, function($i1, $i2) {
            $t = explode('. ',$i1);
            $i1 = (! isset($t[1]) ? $i1 : $t[1]);
            $t = explode('. ',$i2);
            $i2 = (! isset($t[1]) ? $i2 : $t[1]);
            return strcmp(strtoupper($i1), strtoupper($i2));
          });

只是我自己的旋转,应该更灵活一点。工作演示

usort($data, 'sortByName');
function sortByName($a, $b) {
    $remove = [' ', '.', 'Mrs', 'Miss', 'Ms', 'Master', 'Dr', 'Mr'];
    $a = str_replace($remove, '', $a);
    $b = str_replace($remove, '', $b);  
    return strcasecmp($a, $b);
}

唯一需要注意的是,$titles需要按一定的顺序排列,因为Mrs必须始终排在Mr之前,因为MrMrs之内,所以如果你切换顺序,那么Mr可能会被带走,留下一个流氓S

相信这应该适用于你想要的,任何问题让我知道。

编辑已更新。

这是另一种方法,但这次使用正则表达式。如果先生或太太后面没有".",也可以工作

$arrToSort = ["Mr. Bala","Mr. Santhosh","Camel","Mrs. Vinoth","Mr Roger","Mr. Calmator","Janette","Mrs Anne Couture"];
usort($arrToSort, 'ignore_Title');
function ignore_Title($a, $b){
    preg_match("/^Mrs{0,1}'.{0,1} (.*)$|/s",$a,$tmp);
    preg_match("/^Mrs{0,1}'.{0,1} (.*)$|/s",$b,$tmp2);
    return strcasecmp($tmp[1],($tmp2[1] == "" ?  $b : $tmp2[1]));
}
print_r($arrToSort);

输出:

[0] => Mr. Bala
[1] => Camel
[2] => Mr. Calmator
[3] => Janette
[4] => Mrs Lark Obm
[5] => Mr Roger
[6] => Mr. Santhosh
[7] => Mrs. Vinoth