如何编写PHP抽奖概率计算的具体实现类?

更新于
2026-09-26 04:38:11
1阅读来源:SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计172个文字,预计阅读时间需要1分钟。

如何编写PHP抽奖概率计算的具体实现类?

php概率计算类 可用于抽奖等class Probability{ 概率统计数据 var $data=array(); function __construct($initdata=array()) { if (!empty($initdata)) { $this->data=$initdata; } }}

如何编写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"; }

本文共计172个文字,预计阅读时间需要1分钟。

如何编写PHP抽奖概率计算的具体实现类?

php概率计算类 可用于抽奖等class Probability{ 概率统计数据 var $data=array(); function __construct($initdata=array()) { if (!empty($initdata)) { $this->data=$initdata; } }}

如何编写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"; }