本文实例讲述了PHP编程实现计算抽奖概率算法。分享给大家供大家参考,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
<?php //计算抽奖的概率 function get_rand( $proArr ) { $result = '' ; $proSum = array_sum ( $proArr ); foreach ( $proArr as $key => $proCur ) { $randNum = mt_rand(1, $proSum ); if ( $randNum <= $proCur ) { $result = $key ; break ; } else { $proSum -= $proCur ; } } unset ( $proArr ); return $result ; } $prize_arr = array ( '0' => array ( 'id' =>1, 'prize' => '家电' , 'v' =>2), '1' => array ( 'id' =>2, 'prize' => '数码相机' , 'v' =>5), '2' => array ( 'id' =>3, 'prize' => 'iPad' , 'v' =>13), '3' => array ( 'id' =>4, 'prize' => 'LED显示器' , 'v' =>15), '4' => array ( 'id' =>5, 'prize' => 'U盘' , 'v' =>25), '5' => array ( 'id' =>6, 'prize' => '键盘' , 'v' =>30), '6' => array ( 'id' =>7, 'prize' => '鼠标垫' , 'v' =>10), ); foreach ( $prize_arr as $key => $val ) { $arr [ $val [ 'id' ]] = $val [ 'v' ]; } $rid = get_rand( $arr ); $res [ 'yes' ] = $prize_arr [ $rid -1][ 'prize' ]; unset( $prize_arr [ $rid -1]); shuffle( $prize_arr ); $prize_arrcount = count ( $prize_arr ); for ( $i =0; $i < $prize_arrcount ; $i ++){ $pr [] = $prize_arr [ $i ][ 'prize' ]; } $res [ 'no' ] = $pr ; //抽奖结果 $ro = $res [ 'yes' ]; print_r( $ro ); ?> |
运行结果:
1
|
iPad |
PS:这里再为大家提供两款功能类似的在线工具供大家参考:
在线随机字符/随机密码生成工具:https://tool.zzvips.com/t/randkey/
在线随机数生成工具:https://tool.zzvips.com/t/kami/
希望本文所述对大家PHP程序设计有所帮助。
原文链接:http://blog.csdn.net/phpfenghuo/article/details/38491403