Two ways to do this, that I can think of from the top of my head:
Option 1: Fill a new array with the key values from the set of data, where the weight determines how often an item is repeated. The proportion in this array then matches the weighted distribution. Simply grab using $arr[array_rand($arr)]
. While simple and easy to understand, this will explode in your face if there are a LOT of items, or if the weight values are really high.
$weighted = array();
foreach($items as $item) {
array_merge($weighted, array_fill(0, $item['weight'], $item['value']);
}
$result = $weighted[array_rand($weighted)];
Option 2. Sum the weights. Pick a random number between 0 and sum-of-weights. Loop over the elements in the dataset, compare against the random number you picked. As soon as you hit one that is equal to or bigger then the random index, select that element.
function findRandomWeighted(array $input) {
$weight = 0;
// I'm assuming you can get the weight from MySQL as well, so this loop really should not be required. In that case $weight becomes a parameter.
foreach($items as $item) {
$weight += $item['weight'];
}
$index = rand(1, $weight);
foreach($items as $item) {
$index -= $item['weight'];
if($index <= 0) { return $item['value'] }
}
return null;
}
Following our conversation in the comments below, here is a Pastebin with the code in it:
http://pastebin.com/bLbhThhj