2.15 Weighting Random Numbers
TechniquePHP does not have built-in support for this, so we'll just have to roll our own: <?php // // Company -> Weight // $ads = array("Spacely Sprockets" => 1, "The Rock Quarry" => 1, "Springfield Power Plant" => 3, "Microsoft" => 10, "Phillip Morris" => 5); $j = 0; foreach ($ads as $company => $weight) { for ($i=0; $i < $weight; $i++) { $dist[$j++] = $company; } srand((double)microtime()*1000000); $rand_num = mt_rand(0, $j - 1); shuffle($dist); // randomize the array, see chapter 4 for more details $company = $dist[$rand_num]; print "The Selected company was: $company"; ?> CommentsThe previous script takes an array of companies and their respective weights, or how often they should be displayed in relation to each other. For example, Microsoft has a weight of 10, which means that it will be displayed more often than Springfield Power Plant that has a weight of 3. We then initialize a foreach loop and loop through the $ads array. For each element of the $ads array, we put it into a new array for the amount of times specified by weight. For example, Microsoft has ten entries in the $dist array. Finally, we seed the random number generator, pick out a random number that is the bounds of the array, and use that random number ( $rand_num ) as the index for the $dist array. The example is only one method of generating a biased random number; for different methods , you should take a look at your statistics textbook . |