这是我写的一个比较简单的抽奖算法,并没有很严谨,用于我自己写的wap文字游戏(美味小镇)上的随机食材,可以设定概率值 <?php /** * Created by PhpStorm. * User: tioncico * Date: 2017/12/9 0009 * Time: 14:50 */ class Rand { public $arr,$not_id,$if_repeat,$odds; public function __construct($arr,$if_repeat=1) { $this->arr=$arr; $this->if_repeat=$if_repeat; $this->get_odds_array(); } function action($num=1) { if(!$this->arr||!$this->odds){ return false; } $ids = array(); for ($i = 0; $i < $num; $i++) { $res = $this->get_rand($this->arr, $this->odds); if ($this->if_repeat == 0) { if(count($this->arr)<=count($ids)){ return $ids; } if (in_array($res, $ids)) { $i--; } else { $ids[] = $res; } } else { $ids[] = $res; } } return $ids; } public function get_odds_array($arr=array()) { $arr||$arr = $this->arr; foreach ($arr as $k => $va) { if(empty($va['odds'])){ $va['odds']=100; } $odds[$k] = $va['odds']; } $this->odds = array_sum($odds); return $this; } public function add_arr($arr=array()){ $this->arr = array_merge($this->arr,$arr); return $this; } function remove_id($arr=array(),$not_id=array()){ $arr||$arr = $this->arr; $not_id||$not_id = $this->not_id; if(empty($not_id)){ $this->arr = $arr; return $this; } foreach($arr as$k=> $va){ foreach($not_id as $vo){ if($k==$vo){ unset($arr[$k]); } } } $this->arr = $arr; return $this; } //返回概率 function get_rand($arr=array(), $odds=0) { $arr||$arr = $this->arr; $odds||$odds = $this->odds; //概率数组循环 $randNum = mt_rand(1, $odds); $odd_num = 0; foreach ($arr as $key => $va) { if ($randNum > $odd_num && $randNum <= $va['odds'] + $odd_num) { return $arr[$key]; break; } else { $odd_num += $va['odds']; } } unset ($proArr); } } $arr=array( array( 'id'=>1, 'odds'=>100//相对概率值 ), array( 'id'=>2, 'odds'=>10//相对概率值 ), array( 'id'=>3, 'odds'=>200//相对概率值 ), ) 调用方法 $a = new Rand($arr); $a->action(1);