Re: Sorting an array
| From: | Pavel Jartsev | Date: | Tue, 29 Aug 2000 08:05:39 +0000 |
| Subject: | Re: Sorting an array | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-14066@lists.php.net to get a copy of this message | ||
Sebastian Bergmann wrote:
>
> Hi,
>
> I have an array as follows:
>
> $array[ 0 ][ "frequency" ] = 10;
> $array[ 0 ][ "array" ] = array( "test1", "test2" );
> $array[ 1 ][ "frequency" ] = 100;
> $array[ 1 ][ "array" ] = array( "test3" );
>
> Now I have to sort this array by descending frequency
> <skip>...
Hi!
You can do this with 'usort(array array, function cmp_function)',
which needs user-defined compare function.
For example:
<?
/*---- our nice function ----*/
function my_comp ( $a, $b ) {
if ($a['frequency'] == $b['frequency'])
return 0;
return ($a['frequency'] > $b['frequency']) ? -1 : 1;
}
/*---- sort array ----*/
usort( $array, my_comp );
?>
And 'usort()' does whole magic.
See also PHP-manual: 'III. Array functions' -> 'usort'.
Hope this helps.
:-)
--
Pavel a.k.a. Papi