<?php
/**
* @param array $items
* @param array $weights
*
* @return mixed
*/
function random_weighted(array $items, array $weights) {
$weight = 0;
$return = current($items);
for ($i = 0, $n = count($items); $i < $n; $i++) {
$random = mt_rand(0, $weights[$i] + $weight);
if ($random >= $weight) {
$return = $items[$i];
}
$weight += $weights[$i];
}
return $return;
}
$items = ['a', 'b', 'c', 'd'];
$weights = [0, 10, 10, 10];
$i = 100;
$results = ['a' => 0, 'b' => 0, 'c' => 0, 'd' => 0];
do {
$x = random_weighted($items, $weights);
$results[$x]++;
} while (--$i);
var_dump($results);
preferences:
31.51 ms | 402 KiB | 5 Q