我不知道这是否是最好的解决方案,但是当我不久前必须解决这个问题时,我发现了以下内容:
函数取自这篇博文 http://w-shadow.com/blog/2008/12/10/fast-weighted-random-choice-in-php/:
// Given an array of values, and weights for those values (any positive int)
// it will select a value randomly as often as the given weight allows.
// for example:
// values(A, B, C, D)
// weights(30, 50, 100, 25)
// Given these values C should come out twice as often as B, and 4 times as often as D.
function weighted_random($values, $weights){
$count = count($values);
$i = 0;
$n = 0;
$num = mt_rand(0, array_sum($weights));
while($i < $count){
$n += $weights[$i];
if($n >= $num){
break;
}
$i++;
}
return $values[$i];
}
调用示例:
$values = array('A','B','C');
$weights = array(1,50,100);
$weighted_value = weighted_random($values, $weights);
它有点笨拙,因为显然需要单独提供值和权重,但这可能会被重构以满足您的需求。