Home > Backend Development > PHP Tutorial > Sharing examples of how to implement algorithm for calculating lottery probability in PHP

Sharing examples of how to implement algorithm for calculating lottery probability in PHP

黄舟
Release: 2023-03-14 19:48:02
Original
1669 people have browsed it

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 complete examples. Friends in need can refer to it

The examples in this article describe the implementation of PHP programming Algorithm for calculating lottery probability. Share it with everyone for your reference, 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);
?>
Copy after login

Running results:


iPad
Copy after login

The above is the detailed content of Sharing examples of how to implement algorithm for calculating lottery probability in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template