php抽奖概率计算类
<?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";
} 以上就是php抽奖概率计算类的内容,更多相关内容请关注PHP中文网(www.php.cn)!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号