Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // First some SQL to execute
- // You will only need the ALTER and UPDATE, the insert is to generate some example data so we can actually run tests on it.
- /**
- ALTER TABLE `test`.`feeds` ADD COLUMN `weight` SMALLINT NOT NULL DEFAULT 1 AFTER `url`;
- INSERT INTO `feeds` (name, url)
- VALUES
- ('Test 1', 'http://www.google.com/feeds'),
- ('Test 2', 'http://some-url.com'),
- ('Test 3', 'http://feeds-r-us.com'),
- ('Test 4', 'http://even-more-links.com'),
- ('Test 5', 'http://www.veryimportantfeed.com');
- UPDATE `test`.`feeds` SET `weight`=1 WHERE `id`='1'
- UPDATE `test`.`feeds` SET `weight`=1 WHERE `id`='2'
- UPDATE `test`.`feeds` SET `weight`=1 WHERE `id`='3'
- UPDATE `test`.`feeds` SET `weight`=1 WHERE `id`='4'
- UPDATE `test`.`feeds` SET `weight`=6 WHERE `id`='5'
- **/
- function findRandomWeighted(array $items) {
- $maxWeight = 0;
- // Sum all the weights.
- foreach($items as $item) {
- $maxWeight += $item['weight'];
- }
- $index = rand(1, $maxWeight);
- foreach($items as $item) {
- $index -= $item['weight'];
- if($index <= 0) {
- return $item;
- }
- }
- }
- $conn = mysql_connect('localhost','username','password');
- mysql_select_db('test', $conn);
- $query = "SELECT * FROM `feeds`";
- $result = mysql_query($query);
- $data = array();
- while($output = mysql_fetch_assoc($result)) {
- $data[] = $output;
- }
- // Test
- $selections = array(1=>0, 2=>0, 3=>0, 4=>0, 5=>0);
- for($i = 0; $i < 1000; $i++) {
- $feed = findRandomWeighted($data);
- $selections[$feed['id']]++;
- }
- // Result should be approximately equal to the distribution of the weight.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement