3

假设我有一个对象:

$person->name = array('James',
                      'Sam',
                      'Kevin',
                      'Mike');
$person->weight = array(1,
                        3,
                        1,
                        7);

在上面的示例James中,权重为1Sam权重为3等(基于索引位置)

我希望能够只呼应一个人的名字。权重越高,您的名字被选中的机会就越大。权重越低,您的名字被选中的机会就越低。有点像彩票,但有权重。关于如何做到这一点的任何想法?

4

3 回答 3

3

这应该有效:

$weighted = array();
foreach($person->weight as $key => $value) {
    $weighted = array_merge($weighted, array_fill(0, $value, $key));
}
$index = array_rand($weighted);
echo $person->name[$index];

基于这个答案

于 2012-06-01T22:32:14.170 回答
1

创建一个新数组,将名字 Sam 添加到数组中 3 次,mike 7 次,其他一次,然后随机选择一个。

于 2012-06-01T22:31:42.560 回答
1

You could also sum up all the weights and generate a random number between one and that sum. Then you could iterate over the array of weights summing them up until the result is >= the random number and take that person. Might be slightly faster.

于 2012-06-01T22:41:51.543 回答