Home >Backend Development >PHP Tutorial >PHP implements lottery probability calculation algorithm

PHP implements lottery probability calculation algorithm

墨辰丷
墨辰丷Original
2018-05-18 15:20:402372browse

This article mainly introduces PHP programming to implement the calculation of lottery probability algorithm, and analyzes the operation skills related to PHP random number operation in the form of a complete example. Friends in need can refer to it

The details are as follows:

<?php
 //计算抽奖的概率
 function get_rand($proArr) {
 $result = &#39;&#39;;
 $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(
 &#39;0&#39; => array(&#39;id&#39;=>1,&#39;prize&#39;=>&#39;家电&#39;,&#39;v&#39;=>2),
 &#39;1&#39; => array(&#39;id&#39;=>2,&#39;prize&#39;=>&#39;数码相机&#39;,&#39;v&#39;=>5),
 &#39;2&#39; => array(&#39;id&#39;=>3,&#39;prize&#39;=>&#39;iPad&#39;,&#39;v&#39;=>13),
 &#39;3&#39; => array(&#39;id&#39;=>4,&#39;prize&#39;=>&#39;LED显示器&#39;,&#39;v&#39;=>15),
 &#39;4&#39; => array(&#39;id&#39;=>5,&#39;prize&#39;=>&#39;U盘&#39;,&#39;v&#39;=>25),
 &#39;5&#39; => array(&#39;id&#39;=>6,&#39;prize&#39;=>&#39;键盘&#39;,&#39;v&#39;=>30),
 &#39;6&#39; => array(&#39;id&#39;=>7,&#39;prize&#39;=>&#39;鼠标垫&#39;,&#39;v&#39;=>10),
 );
 foreach ($prize_arr as $key => $val) {
 $arr[$val[&#39;id&#39;]] = $val[&#39;v&#39;];
 }
 $rid = get_rand($arr);
 $res[&#39;yes&#39;] = $prize_arr[$rid-1][&#39;prize&#39;];
 unset($prize_arr[$rid-1]);
 shuffle($prize_arr);
 $prize_arrcount = count($prize_arr);
 for($i=0;$i<$prize_arrcount;$i++){
 $pr[] = $prize_arr[$i][&#39;prize&#39;];
 }
 $res[&#39;no&#39;] = $pr;
 //抽奖结果
 $ro = $res[&#39;yes&#39;];
 print_r($ro);
?>

Run result:

iPad

Related recommendations:

PHP Probability calculation function

Summary of PHP probability calculation function,php probabilityfunction_PHP tutorial

# #Examples of PHP probability algorithm suitable for lottery programs and random advertisements_PHP tutorial

The above is the detailed content of PHP implements lottery probability calculation algorithm. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn