Blogger Information
Blog 47
fans 0
comment 2
visits 102571
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
php抽奖概率算法
拾一枝樱花的博客
Original
1697 people have browsed it

一、方法一

function get_rand($proArr) {

  $result = array();

  foreach ($proArr as $key => $val) {

    $arr[$key] = $val['v'];

  }

  // 概率数组的总概率

  $proSum = array_sum($arr);

  asort($arr);

  // 概率数组循环

  foreach ($arr as $k => $v) {

    $randNum = mt_rand(1, $proSum);

    if ($randNum <= $v) {

      $result = $proArr[$k];

      break;

    } else {

      $proSum -= $v;

    }

  }

  return $result;

}

$arr = array(

  array('id'=>1,'name'=>'特等奖','v'=>1),

  array('id'=>2,'name'=>'一等奖','v'=>5),

  array('id'=>3,'name'=>'二等奖','v'=>10),

  array('id'=>4,'name'=>'三等奖','v'=>12),

  array('id'=>5,'name'=>'四等奖','v'=>22),

  array('id'=>6,'name'=>'没中奖','v'=>50)

);

var_dump(get_rand($arr));



二、方法二

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;

}

$arr = array(

  array('id'=>1,'name'=>'特等奖','v'=>1),

  array('id'=>2,'name'=>'一等奖','v'=>5),

  array('id'=>3,'name'=>'二等奖','v'=>10),

  array('id'=>4,'name'=>'三等奖','v'=>12),

  array('id'=>5,'name'=>'四等奖','v'=>22),

  array('id'=>6,'name'=>'没中奖','v'=>50)

);

foreach ($arr as $val) {

        $item[$val['id']] = $val['v'];

}

var_dump(get_rand($item));


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post