Andreas Korthaus: Strings in einem Array sortieren

Beitrag lesen

Hi!

Hast Du mal die Kommentare gelesen?(http://www.php.net/manual/de/function.sort.php) Solltest Du tun, denn da stehen mehrere Lösungen:

##################################################################################################

tim at sod dot co dot uk
26-Mar-2001 07:40
I was looking for a way to sort an array alphabetically. The first post points out that 'Ab' is different to 'AB' and you can't make it case insensitive (well, I couldn't). So I did it like this:

function cmp ($a, $b) {
$tmp[0]=strtoupper($a);
$tmp[1]=strtoupper($b);
sort($tmp);
return (strcmp(strtoupper($tmp[1]) , strtoupper($b))) ? 1 : -1;
}

$listing[0]="AB";
$listing[1]="yzZAZz";
$listing[2]="YZzazZ";
$listing[3]="LhaASD";
$listing[4]="A";
$listing[5]="aB";

usort($listing, "cmp");

echo implode(",",$listing);

Which produces:
A,AB,aB,LhaASD,yzZAZz,YZzazZ

##################################################################################################

peek at mailandnews dot com
07-Apr-2001 05:06
I ran into the same problem with case insensitive sorting. Actually I think there should be a SORT_STRING_CASE flag but I tried the following:

usort($listing, 'strcasecmp');

This didn't work (why not?), but you can do a proper case insensitive sort like this:

usort($listing, create_function('$a,$b','return strcasecmp($a,$b);'));

##################################################################################################

kevj at shaw dot ca
25-Feb-2002 08:10
fwiw, usort($listing, 'strcasecmp'); works as expected now (php 4.1.1 and possibly earlier versions)

##################################################################################################

Folgendes Script:

<?php
$test[0]="B";
$test[1]="a";
$test[2]="b";
$test[3]="A";
$test[4]="BB";
$test[5]="AA";

usort($test, 'strcasecmp');
print_r($test);
?>

erzeugt bei mir folgende Ausgabe:

Array
(
    [0] => A
    [1] => a
    [2] => AA
    [3] => b
    [4] => B
    [5] => BB
)

(unter 4.2.4-dev)

und komischerweise

Array
(
    [0] => a
    [1] => A
    [2] => AA
    [3] => B
    [4] => b
    [5] => BB
)
(unter 4.1.2)

Das ist ja beides falsch, vermutlich ein PHP-Bug! Daher würde ich mal eine der anderen Funktionen testen!

Grüße
Andreas

PS: Wie im Kommentar steht natürlich erst ab PHP-Version 4.1.1