php简单计算权重的方法示例【适合抽奖类应用】

时间:2022-11-26 17:57:18

本文实例讲述了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
//简单权重计算器
$data222=array(
  0=>array('id'=>1,'name'=>'一等奖','weight'=>'3'),
  1=>array('id'=>2,'name'=>'二等奖','weight'=>'1'),
  2=>array('id'=>3,'name'=>'三等奖','weight'=>'5'),
  3=>array('id'=>3,'name'=>'三等奖','weight'=>'1'),
);
// 权重数值越高,被返回的概率越大
// 原理生成权重个数的数组字,入array(5个0,10个1,25个2)
function countWeight($data){
  $i=0;
  $temp=array();
  foreach($data as $v){
    for($i=0;$i<$v['weight'];$i++){
      $temp[]=$v;//放大数组
    }
  }
  $num = count($temp);  //查看网上的有错误,本人已改正
  $int=mt_rand(0,$num-1);//获取一个随机数
  $result=$temp[$int];
  return $result//返回一维数组
}
echo '<pre>';
var_dump(countWeight($data222));

执行后的效果为

array(3) {
  ["id"]=>
  int(2)
  ["name"]=>
  string(9) "二等奖"
  ["weight"]=>
  string(2) "10"
}

希望本文所述对大家PHP程序设计有所帮助。

原文链接:https://blog.csdn.net/u010071211/article/details/79626899