内容详情 您现在的位置是: 首页> PHP

php 抽奖概率 随机数

发布时间:2020-11-23 19:23 已围观:4082

摘要php 抽奖概率 随机数

<?php
$prize_arr = array(
   '0' => array('id' => 1, 'title' => 'iphone5s', 'v' => 5),
   '1' => array('id' => 2, 'title' => '联系笔记本', 'v' => 10),
   '2' => array('id' => 3, 'title' => '音箱设备', 'v' => 20),
   '3' => array('id' => 4, 'title' => '30GU盘', 'v' => 30),
   '4' => array('id' => 5, 'title' => '话费50元', 'v' => 10),
   '5' => array('id' => 6, 'title' => 'iphone6s', 'v' => 15),
   '6' => array('id' => 7, 'title' => '谢谢,继续加油哦!~', 'v' => 10),
);

foreach ($prize_arr as $key => $val) {
   $arr[$val['id']] = $val['v'];
}

$prize_id = getRand($arr); //根据概率获取奖品id
$data['msg'] = ($prize_id == 7) ? 0 : 1; //如果为0则没中  
$data['prize_title'] = $prize_arr[$prize_id - 1]['title']; //中奖奖品
echo json_encode($data);
exit; //以json数组返回给前端

function getRand($proArr) { //计算中奖概率
   $rs = ''; //z中奖结果
   $proSum = array_sum($proArr); //概率数组的总概率精度
   //概率数组循环
   foreach ($proArr as $key => $proCur) {
       $randNum = mt_rand(1, $proSum);
       if ($randNum <= $proCur) {
           $rs = $key;
           break;
      } else {
           $proSum -= $proCur;
      }
  }
   unset($proArr);
   return $rs;
}
<?php
header("Content-Type: text/html; charset=utf-8");
$prize_arr = array(
 '0' => array(
     'id' => 1,
     'url' => 'http://mp.weixin.qq.com/s/hyPRO4tJAl1cJaY97TGFvw', 'v' => 5
),
 '1' => array(
     'id' => 2,
      'url' => 'http://mp.weixin.qq.com/s/gD2MhdYAMx1PyA4jCdJtQQ',
     'v' => 10
),
 '2' => array(
     'id' => 3,
     'url' => 'http://mp.weixin.qq.com/s/Ud_F_l6ZufGElkZwONzGbA',
     'v' => 20
),
 '3' => array(
     'id' => 4,
     'url' => 'http://mp.weixin.qq.com/s/LA1lASoxuRdaZ13F8pQbNA',
     'v' => 30
),
 '4' => array(
     'id' => 5,
     'url' => 'http://mp.weixin.qq.com/s/efZKG9GjrchhBR4zT5zU3A',
     'v' => 10
),
 '5' => array(
     'id' => 6,
     'url' => 'http://mp.weixin.qq.com/s/ghisPsLG4OIFdehn6kZrUw',
     'v' => 15
),
 '6' => array(
     'id' => 7,
     'url' => 'http://mp.weixin.qq.com/s/bltFJBXstWN43r0GiePzBw',
     'v' => 10
),
);
// echo "呵呵";
foreach ($prize_arr as $key => $val) {
 $arr[$val['id']] = $val['v'];
}
// var_dump($arr);

$myid = myword($arr);
$data['url'] = $prize_arr[$myid-1]['url'];
$url = $data['url'];
echo "<script type='text/javascript'>window.location.href='$url';</script>";

function myword($str){
$rs = '';//中奖结果
$proSum = array_sum($str);//计算数组中所有值的和
   //概率数组循环
foreach ($str as $k => $v) {
  $word1 = mt_rand(1,$proSum);  //生成更好的随机数
       if( $word1 <= $v){
          $rs = $k;
          break;
      }else{
          $proSum -= $v;
      }
  }
return $rs;
}

声明:本文内容摘自网络,版权归原作者所有。如有侵权,请联系处理,谢谢~
转发:https://www.cnblogs.com/vip-deng-vip/p/8032053.html

赞一个 (26)