0

I am trying to sort an array of student names alphabetically. In the array we have $user['firstname'] and $user['lastname']. I want to sort it such that A/a comes first and then Z/z comes last. If their first names are the same then we compare with last name. My problem is that I've already created the functionality for this sorting but it is not case insensitive.

This is what I've done so far:

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

Thanks for your help.

4

2 に答える 2

2

次に例を示します。

usort($students, function($a, $b) {
  if($cmp = strnatcasecmp($a['lastname'], $b['lastname'])) return $cmp;
  return strnatcasecmp($a['firstname'], $b['firstname']);
});
于 2014-03-18T20:48:12.113 に答える
-3

strtolower関数が役立つと思います。関数の最初にこれを追加するだけです:

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

これを行うことにより、すべての値を小文字に変換し、関数の「感度」を取り除きます。

それが役に立てば幸い。

于 2012-05-20T11:36:38.240 に答える