Home >Backend Development >PHP Tutorial >Detailed explanation of php winning algorithm
This article mainly brings you a simple PHP winning algorithm (example). The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor to take a look, I hope it can help everyone.
I encountered such a problem today. Encapsulate a lottery probability function. After thinking about it, go to the Internet to find some information. There is more than one method. I feel it is relatively easy. It is still the idea of implementing the function. There is more than one code and more than one.
function get_rand($proArr) { $result = ''; //概率数组的总概率精度 $proSum = array_sum($proArr); //概率数组循环 foreach ($proArr as $key => $proCur) { $randNum = mt_rand(1, $proSum); if ($randNum <= $proCur) { $result = $key; break; } else { $proSum -= $proCur; } } unset ($proArr); return $result; } $prize_arr = array( '0' => array('id'=>1,'prize'=>'平板电脑','v'=>0.1), '1' => array('id'=>2,'prize'=>'数码相机','v'=>5), '2' => array('id'=>3,'prize'=>'音箱设备','v'=>10), '3' => array('id'=>4,'prize'=>'4G优盘','v'=>12), '4' => array('id'=>5,'prize'=>'10Q币','v'=>22), '5' => array('id'=>6,'prize'=>'下次没准就能中哦','v'=>50), ); foreach ($prize_arr as $key => $val) { $arr[$val['id']] = $val['v']; } $rid = get_rand($arr); //根据概率获取奖项id $res['yes'] = $prize_arr[$rid-1]['prize']; //中奖项 unset($prize_arr[$rid-1]); //将中奖项从数组中剔除,剩下未中奖项 shuffle($prize_arr); //打乱数组顺序 for($i=0;$i<count($prize_arr);$i++){ $pr[] = $prize_arr[$i]['prize']; } $res['no'] = $pr; echo json_encode($res,JSON_UNESCAPED_UNICODE);
Related recommendations:
Example of php implementing lottery program winning probability algorithm
php Winning Probability Algorithm Implementation Code
PHP Lottery Algorithm Program Code for Winning Probability_PHP Tutorial
The above is the detailed content of Detailed explanation of php winning algorithm. For more information, please follow other related articles on the PHP Chinese website!