note 16815 added to function.usort

From: Date: Wed, 14 Nov 2001 17:48:42 +0000
Subject: note 16815 added to function.usort
Groups: php.notes 
Request: Send a blank email to php-notes+get-20840@lists.php.net to get a copy of this message
Here's a variation on the multi- dimensional sorts above, but with more flexibility and speed. Note that this version only leverages strcmp() to compare array values, which is sufficient for most cases. /** * arfsort() - (AR)ray (F)ield Sort. * Sort a multi-dimensional array according * to a list of fields. * @param $a The array to sort * @param $fl Field list (in order of importance) */ function arfsort( $a, $fl ) {  $GLOBALS['__ARFSORT_LIST__'] = $fl; usort( $a, 'arfsort_func' ); return $a; } /** * Internal sorting function for arfsort() */ function arfsort_func( $a, $b ) { foreach( $GLOBALS['__ARFSORT_LIST__'] as $f ) { $strc = strcmp( $a[$f], $b[$f] ); if ( $strc != 0 ) { return $strc; } } return 0; } // Example usage $test = array( array( 'fruit' => 'apple', 'type' => 'sweet' ), array( 'fruit' => 'green apple', 'type' => 'sour' ), array( 'fruit' => 'lemon', 'type' => 'sour' ) ); $sorted = arfsort( $test, array( 'type', 'fruit' ) ); // Returned array should be sorted // with the green apple data first, then the // lemon, then the apple. Awesome for sorting SQL result sets. -- http://www.php.net/manual/en/function.usort.php http://master.php.net/manage/user-notes.php?action=edit+16815 http://master.php.net/manage/user-notes.php?action=delete+16815 http://master.php.net/manage/user-notes.php?action=reject+16815

« previous php.notes (#20840) next »