- <?php
- /**
- * 概率计算类
- * 可用于抽奖等
- */
- class Probability
- {
- /**
- * 概率统计数据
- * thing => chance
- */
- var $data = array();
- var $chance_count = 0;
- function __construct($initdata = array()){
- if(!empty($initdata)){
- $this->data = $initdata;
- foreach($initdata as $d){
- $this->chance_count += $d['num'];
- }
- }
- }
- function addData($name, $chance){
- $this->data[]=array('name'=>$name, 'num'=>$chance);
- $this->chance_count += $chance;
- }
- function getOne(){
- $index = rand(0, $this->chance_count);
- foreach($this->data as $d){
- $index = $index-$d['num'];
- if($index<=0){
- return $d['name'];
- }
- }
- return '';
- }
- }
- /**
- * 使用示例
- */
- $pro=new Probability();
- $pro->addData('iphone',10);
- $pro->addData('watch',30);
- $pro->addData('$18',50);
- $pro->addData('thank you',10);
- $pro->addData('super big',1);
- for($i=0;$i<100;$i++){
- echo $pro->getOne()."\\n";
- }
- //该片段来自于http://www.codesnippet.cn/detail/1507201513104.html
来源: http://www.codesnippet.cn/detail/1507201513104.html