```
public function controllableProbability($arr, $weight_key = 'weight') {
$total_probability = 0;
foreach($arr as $v) {
$total_probability = bcadd((string)$total_probability, (string)$v[$weight_key], 2);
}
$rand = mt_rand(1, intval($total_probability));
foreach ($arr as $val) {
if ($rand <= $val[$weight_key]) {break;}
$rand -= $val[$weight_key];
next($arr);
}
return current($arr);
}
public function test1()
{
$arr = [
['id' => 1, 'name' => '谢谢惠顾', 'weight' => 10],
['id' => 2, 'name' => '中10元', 'weight' => 5],
['id' => 3, 'name' => '中2元', 'weight' => 1],
['id' => 4, 'name' => '中50W', 'weight' => 0],
];
$result = $this->controllableProbability($arr);
return $result['name'];
$a = 0; $b = 0; $c = 0; $d = 0;
for($i = 0; $i < 160000; $i++) {
$res = $this->controllableProbability($arr, 'weight');
if($res['id'] == 1) $a ++;
if($res['id'] == 2) $b ++;
if($res['id'] == 3) $c ++;
if($res['id'] == 4) $d ++;
}
echo "$a $b $c $d";
}