//key:奖项 key,value:中奖的概率占比或者份数
$array = ['key1' => 20, 'key2' => 40, 'key3' => 30, 'key5' => 10];
//return:返回中奖的 key
$fun = function ($array) {asort($array);// 概率大小排序,调配区间,0-10-20-30-40;
$randNum = mt_rand(1, array_sum($array));// 随机数
//print_r($randNum . PHP_EOL);
// 区间判断
$start = 0;
foreach ($array as $key => $item) {
// 结构区间数:0-10-20-30-40;
$start += $item;
//print_r('start:' . $start . 'key:' . $key . PHP_EOL);
if ($randNum <= $start) {return $key;}
}
};
var_dump($fun($array));