note 16815 deleted from function.usort by danbrown

From: Date: Sun, 23 Jan 2011 16:32:11 +0000
Subject: note 16815 deleted from function.usort by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-176084@lists.php.net to get a copy of this message
Note Submitter: jonathan at inetz dot com ---- 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.

« previous php.notes (#176084) next »