douchen2011 2017-06-28 02:24
浏览 78

PHP在小写字符之前排序大写字符

I'm using PHP and having problems with different sorting functions, such as sort and usort. Here is an example.

$taulu[] = "Ahola";
$taulu[] = "AL-mara";
$taulu[] = "Aalto";
$taulu[] = "A. Pek";

sort($taulu);

foreach ($taulu as $rivi)
{
  echo "$rivi<br />";
}

This will print:

A. Pek
AL-mara
Aalto
Ahola

I want it to be this way:

A. Pek
Aalto
Ahola
AL-mara

How could that be possible?

Update

$taulu[] = "Ahola";
$taulu[] = "AL-mara";
$taulu[] = "Aalto";
$taulu[] = "A. Pek";
$taulu[] = "AaltoNen";
$taulu[] = "Aalto nen";

sort($taulu, SORT_NATURAL | SORT_FLAG_CASE);

print_r($taulu);

On https://3v4l.org/sZdfa the output on the section "Output for hhvm-3.10.1 - 3.19.0, 7.0.0 - 7.2.0alpha2" is incorrect, but on the section "Output for 5.4.0 - 5.6.30" the output is 100% correct. When using PHP 5.6.23 on https://eval.in, the code works fine. Anyway, on my server with PHP 5.6.30 this does not work.

So, why does this not work in all cases?

  • 写回答

3条回答 默认 最新

  • doufen2769 2017-06-28 02:30
    关注

    The reason your array is sorted that way is because PHP will sort Uppercase characters before lowercase ones.

    One solution to this would be to just compare the strings in a case-insensitive manner, using strcasecmp as a comparison function.

    You can try this:

    usort($array, strcasecmp); // Sort array using `strcasecmp` as the comparison function
    
    评论

报告相同问题?