【问题标题】:How would I sort names (first and last name) alphabetically in PHP, case insensitive?如何在 PHP 中按字母顺序对名称(名字和姓氏)进行排序,不区分大小写?
【发布时间】:2012-05-20 11:31:44
【问题描述】:

我正在尝试按字母顺序对一组学生姓名进行排序。在数组中,我们有 $user['firstname'] 和 $user['lastname']。我想对它进行排序,使 A/a 先出现,然后 Z/z 出现在最后。如果他们的名字相同,那么我们将与姓氏进行比较。我的问题是我已经为这种排序创建了功能,但它不区分大小写。

这是我到目前为止所做的:

uasort($students, array($this, 'nameCompare'));
private function nameCompare($a, $b)
{
    if ($a['firstname'] == $b['firstname']) 
    {
        if($a['lastname'] < $b['lastname'])
        {
            return -1;
        }
        else if ($a['lastname'] > $b['lastname'])
        {
            return 1;
        }
        else //last name and first name are the same
        {
            return 0;
        }
    }
    return ($a['firstname'] < $b['firstname']) ? -1 : 1;
}

感谢您的帮助。

【问题讨论】:

标签: php sorting alphabetical


【解决方案1】:

这是一个例子:

usort($students, function($a, $b) {
  if($cmp = strnatcasecmp($a['lastname'], $b['lastname'])) return $cmp;
  return strnatcasecmp($a['firstname'], $b['firstname']);
});

【讨论】:

    【解决方案2】:

    我认为strtolower 函数可能很有用。在函数的开头添加以下内容:

    $a['firstname'] = strtolower($a['firstname']);
    $a['lastname'] = strtolower($a['lastname']);
    $b['firstname'] = strtolower($b['firstname']);
    $b['lastname'] = strtolower($b['lastname']);
    

    通过这样做,您将所有值转换为小写,消除了函数的“敏感性”。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2020-09-10
      • 2013-11-30
      • 2018-02-28
      • 1970-01-01
      • 2010-10-26
      • 1970-01-01
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多