MediaWiki
REL1_23
|
00001 <?php 00028 class ArrayUtils { 00049 public static function consistentHashSort( &$array, $key, $separator = "\000" ) { 00050 $hashes = array(); 00051 foreach ( $array as $elt ) { 00052 $hashes[$elt] = md5( $elt . $separator . $key ); 00053 } 00054 uasort( $array, function ( $a, $b ) use ( $hashes ) { 00055 return strcmp( $hashes[$a], $hashes[$b] ); 00056 } ); 00057 } 00058 00066 public static function pickRandom( $weights ) { 00067 if ( !is_array( $weights ) || count( $weights ) == 0 ) { 00068 return false; 00069 } 00070 00071 $sum = array_sum( $weights ); 00072 if ( $sum == 0 ) { 00073 # No loads on any of them 00074 # In previous versions, this triggered an unweighted random selection, 00075 # but this feature has been removed as of April 2006 to allow for strict 00076 # separation of query groups. 00077 return false; 00078 } 00079 $max = mt_getrandmax(); 00080 $rand = mt_rand( 0, $max ) / $max * $sum; 00081 00082 $sum = 0; 00083 foreach ( $weights as $i => $w ) { 00084 $sum += $w; 00085 # Do not return keys if they have 0 weight. 00086 # Note that the "all 0 weight" case is handed above 00087 if ( $w > 0 && $sum >= $rand ) { 00088 break; 00089 } 00090 } 00091 00092 return $i; 00093 } 00094 00112 public static function findLowerBound( $valueCallback, $valueCount, $comparisonCallback, $target ) { 00113 if ( $valueCount === 0 ) { 00114 return false; 00115 } 00116 00117 $min = 0; 00118 $max = $valueCount; 00119 do { 00120 $mid = $min + ( ( $max - $min ) >> 1 ); 00121 $item = call_user_func( $valueCallback, $mid ); 00122 $comparison = call_user_func( $comparisonCallback, $target, $item ); 00123 if ( $comparison > 0 ) { 00124 $min = $mid; 00125 } elseif ( $comparison == 0 ) { 00126 $min = $mid; 00127 break; 00128 } else { 00129 $max = $mid; 00130 } 00131 } while ( $min < $max - 1 ); 00132 00133 if ( $min == 0 ) { 00134 $item = call_user_func( $valueCallback, $min ); 00135 $comparison = call_user_func( $comparisonCallback, $target, $item ); 00136 if ( $comparison < 0 ) { 00137 // Before the first item 00138 return false; 00139 } 00140 } 00141 return $min; 00142 } 00143 00157 public static function arrayDiffAssocRecursive( $array1 ) { 00158 $arrays = func_get_args(); 00159 array_shift( $arrays ); 00160 $ret = array(); 00161 00162 foreach ( $array1 as $key => $value ) { 00163 if ( is_array( $value ) ) { 00164 $args = array( $value ); 00165 foreach ( $arrays as $array ) { 00166 if ( isset( $array[$key] ) ) { 00167 $args[] = $array[$key]; 00168 } 00169 } 00170 $valueret = call_user_func_array( __METHOD__, $args ); 00171 if ( count( $valueret ) ) { 00172 $ret[$key] = $valueret; 00173 } 00174 } else { 00175 foreach ( $arrays as $array ) { 00176 if ( isset( $array[$key] ) && $array[$key] === $value ) { 00177 continue 2; 00178 } 00179 } 00180 $ret[$key] = $value; 00181 } 00182 } 00183 00184 return $ret; 00185 } 00186 }