貌似有些不合理,麻烦大家帮忙指正指正!谢谢~
<?php header("content-type:text/html;charset=utf-8"); function getv($k,$arr){ for($j=$k;$j>=0;$j--){ if($j==0){ $tmp[‘b‘]=intval(0); $tmp[‘e‘]=intval($arr[$j][‘v‘]); return $tmp; }else{ $tmp[‘b‘]=intval($arr[$j-1][‘e‘]); $tmp[‘e‘]=intval($arr[$j-1][‘e‘]+$arr[$j][‘v‘]); return $tmp; } } } function dorand(){ //奖品 $prize_arr = array( ‘0‘ => array(‘id‘=>1,‘prize‘=>‘平板电脑‘,‘v‘=>3), ‘1‘ => array(‘id‘=>2,‘prize‘=>‘数码相机‘,‘v‘=>5), ‘2‘ => array(‘id‘=>3,‘prize‘=>‘音箱设备‘,‘v‘=>10), ‘3‘ => array(‘id‘=>4,‘prize‘=>‘4G优盘‘,‘v‘=>12), ‘4‘ => array(‘id‘=>5,‘prize‘=>‘Q币10元‘,‘v‘=>20), ‘5‘ => array(‘id‘=>6,‘prize‘=>‘下次没准就能中哦‘,‘v‘=>50), ); //计算概率范围 for($i=0;$i<count($prize_arr);$i++){ $tmp = getv($i,$prize_arr); $prize_arr[$i][‘b‘] = $tmp[‘b‘]; $prize_arr[$i][‘e‘] = $tmp[‘e‘]; } //获取概率 foreach ($prize_arr as $key => $val) { $arr[$val[‘id‘]][‘v‘] = $val[‘v‘]; $arr[$val[‘id‘]][‘b‘] = $val[‘b‘]; $arr[$val[‘id‘]][‘e‘] = $val[‘e‘]; $arr[$val[‘id‘]][‘prize‘] = $val[‘prize‘]; //获取概率总和 $sum +=$arr[$val[‘id‘]][‘v‘]; } ///产生随机数 $r = mt_rand(1, $sum); //var_dump($arr); //遍历数据 foreach($arr as $k=>$v){ //exit; //判断概率区间 if(($v[‘b‘]<=$r && $v[‘e‘]>=$r)){ echo "随机数:".$r . "\t" . "概率".$v[‘b‘]."--".$v[‘e‘] . "\t"."总概率:".$sum. "\n"; //返回中奖id $id = $k; return $prize = $arr[$k][‘prize‘]; break; } } } for($z=1;$z<=3;$z++){ echo "\r\n第【".$z."】次中奖奖品为:".dorand()."<p>"; } ?>
原文:http://www.cnblogs.com/phpfensi/p/3849265.html