On Thu, 13 Feb 2003, Sean Brown wrote:

> Let's say I've got an array like so:
>
> $myarray[0]["firstname"] = "Mickey";
> $myarray[0]["lastname"] = "Mouse";
> $myarray[0]["score"] = 20;
>
> $myarray[1]["firstname"] = "Donald";
> $myarray[1]["lastname"] = "Duck";
> $myarray[1]["score"] = 10;
>
> I'd like be able to sort the array using different dimensions before I
> cycle through a while loop to print out the results.  For instance, by
> lastname, or by score.  I can't seem to get array_multisort() to do it.

array_multisort() isn't what you want.

> Any ideas?

I've seen this question too many times go through here w/ lots of links,
and no code ... so here ya go.  (And I think someone else asked a similar
question today too ... you too, listen up ;)

You can use the usort() function to your advantage.  This is how:

<?php
// your $myarray definition here, unmodified

$sortKey = "score";
function myCompare( $arrayA, $arrayB ){
        global $sortKey;
        if( $arrayA[$sortKey] == $arrayB[$sortKey] )
                return 0;
        return( $arrayA[$sortKey] < $arrayB[$sortKey] ? -1 : 1 );
}

usort( $myarray, "myCompare" );

var_dump( $myarray );
?>

Obviously, you could sort by the other keys by changing the value
of $sortKey, in the code above, or sort in reverse order by flipping
the inequality comparison operator in myCompare().

http://www.php.net/manual/en/function.usort.php ... for all your usort()
goodness.

        g.luck,
        ~Chris



-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to