MediaWiki  REL1_21
ArrayUtils.php
Go to the documentation of this file.
00001 <?php
00002 
00003 class ArrayUtils {
00024         public static function consistentHashSort( &$array, $key, $separator = "\000" ) {
00025                 $hashes = array();
00026                 foreach ( $array as $elt ) {
00027                         $hashes[$elt] = md5( $elt . $separator . $key );
00028                 }
00029                 uasort( $array, function ( $a, $b ) use ( $hashes ) {
00030                         return strcmp( $hashes[$a], $hashes[$b] );
00031                 } );
00032         }
00033 
00042         public static function pickRandom( $weights ){
00043                 if ( !is_array( $weights ) || count( $weights ) == 0 ) {
00044                         return false;
00045                 }
00046 
00047                 $sum = array_sum( $weights );
00048                 if ( $sum == 0 ) {
00049                         # No loads on any of them
00050                         # In previous versions, this triggered an unweighted random selection,
00051                         # but this feature has been removed as of April 2006 to allow for strict
00052                         # separation of query groups.
00053                         return false;
00054                 }
00055                 $max = mt_getrandmax();
00056                 $rand = mt_rand( 0, $max ) / $max * $sum;
00057 
00058                 $sum = 0;
00059                 foreach ( $weights as $i => $w ) {
00060                         $sum += $w;
00061                         # Do not return keys if they have 0 weight.
00062                         # Note that the "all 0 weight" case is handed above
00063                         if ( $w > 0 && $sum >= $rand ) {
00064                                 break;
00065                         }
00066                 }
00067                 return $i;
00068         }
00069 }