2
我想找出一种方法来选择一定比例的特定数组项目。因此,让我们说:PHP选择数组项目时间百分比?
$testArray = array('item1', 'item2', 'item3', 'item4', 'item5');
现在我会怎么去让item1选择让40%的时间。我知道这可能很容易,但我今天似乎无法将其包围。
我想找出一种方法来选择一定比例的特定数组项目。因此,让我们说:PHP选择数组项目时间百分比?
$testArray = array('item1', 'item2', 'item3', 'item4', 'item5');
现在我会怎么去让item1选择让40%的时间。我知道这可能很容易,但我今天似乎无法将其包围。
随着这些百分比:
$chances = array(40,15,15,15,15);
选择1和100之间的随机数:
$rand = rand(1,100);
而选择根据数组项:
| item1 | item2 | item3 | item4 | item5 |
0 40 55 70 85 100
$ref = 0;
foreach ($chances as $key => $chance) {
$ref += $chance;
if ($rand <= $ref) {
return $testArray[$key];
}
}
POSS对于更一般的溶液IBLE改进:
array_sum()
代替100
$chances
具有相同的键作为输入数组(即与array_keys
和array_combine
)
+1对于好的和简单的逻辑 – 2013-03-12 07:46:01