1

配列をアルファベットで並べ替えたい

asort()を使用すると、その並べ替えが行われますが、最初に得られる結果は、名前が大文字で、その後、すべての名前が小文字になります。

お気に入り :

Avi
Beni
..
..
avi
beni

私が好きなら:

Avi
avi
Beni
beni
..
..

どうすればいいですか?

4

3 に答える 3

4

を使用できますnetcasesort()。大文字と小文字を区別しない「自然順序」アルゴリズムを使用して配列をソートします。

このようにしてください:

natcasesort($array);
于 2010-09-13T07:55:19.063 に答える
2

natcasesort

于 2010-09-13T07:54:44.683 に答える
2

提案されたソリューションは、これまで、正しい、natcasesortおよびusort($ arr、'strcasecmp')ソリューションが、いくつかの開始アレイ構成で失敗しています。

解決策を見つけるために、いくつかのテストを行いましょう。

<?php
$array1 = $array2 = $array3 = $array4 = $array5 = array('IMG1.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG2.png');

// This result is the one we nee to avoid
sort($array1);
echo "Standard sorting\n";
print_r($array1);

// img2.png and IMG2.png are not in the desired order
// note also the array index order in the result array
natcasesort($array2);
echo "\nNatural order sorting (case-insensitive)\n";
print_r($array2);

// img1.png and IMG1.png are not in the desired order
usort($array3, 'strcasecmp');
echo "\nNatural order sorting (usort-strcasecmp)\n";
print_r($array3);

// Required function using the standard sort algorithm
function mySort($a,$b) {
  if (strtolower($a)== strtolower($b))
    return strcmp($a,$b);
  return strcasecmp($a,$b);
}

usort($array4, 'mySort');
echo "\nStandard order sorting (usort-userdefined)\n";
print_r($array4);

// Required function using the natural sort algorithm
function myNatSort($a,$b) {
  if (strtolower($a)== strtolower($b))
    return strnatcmp($a,$b);
  return strnatcasecmp($a,$b);
}

usort($array5, 'myNatSort');
echo "\nNatural order sorting (usort-userdefined)\n";
print_r($array5);

?>

于 2010-09-13T08:20:34.443 に答える