2010-09-13 8 views
1

je veux trier un tableau par ordre alphabétiquephp problème de tri du tableau

quand j'utilise asort() le tri, mais les résultats que je reçois est d'abord, les noms majuscules, et après que tous les les noms avec minuscules

comme:

Avi 
Beni 
.. 
.. 
avi 
beni 

si je veux aimer:

Avi 
avi 
Beni 
beni 
.. 
.. 

comment puis-je fais le ?

Répondre

2

Les solutions proposées, jusqu'à présent, ne coûtent pas correct, natcasesort et usort ($ arr, 'strcasecmp') solutions échouent avec certaines configurations de tableau à partir .

Faisons quelques tests pour trouver une solution.

<?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); 

?>

2
+0

Il ne fonctionne pas. Essayez de trier ce tableau: array ('IMG1.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG2.png'); – Eineki

4

Vous pouvez utiliser netcasesort(). Il trier un tableau en utilisant un algorithme "ordre naturel" insensible à la casse.

le faire comme ceci:

natcasesort($array); 
+1

+1 pour ajouter une réponse réelle au lieu du lien – Gordon

+0

Cela ne fonctionne pas. Essayez de trier ce tableau: array ('IMG1.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG2.png'); – Eineki