$list = [
[
'pt' => 1, //权重序号
'pv' => 0, //权重值
],
[
'pt' => 2,
'pv' => 10,
],
[
'pt' => 3,
'pv' => 20,
],
[
'pt' => 4,
'pv' => 30,
],
[
'pt' => 5,
'pv' => 40,
],
];
print_r(getWeight($list));
function getWeight($list){
$minDefault = $min = 0;
foreach ($list as $key => $val) {
$list[$key]['min'] = $minDefault;
$minDefault += $val['pv'];
$list[$key]['max'] = $minDefault;
}
$max = max(array_unique(array_values(array_column($list, 'max'))));
$rand = rand($min, $max);
$pt = 0;
foreach ($list as $item) {
if($item['min'] < $rand && $item['max'] >= $rand){
$pt = $item['pt'];
break;
}
}
return [$rand, $pt];
}
转载于:https://my.oschina.net/shmilyle/blog/3004474