php 简单计算权重的方法,适合抽奖类的应用

//简单权重计算器
$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"
}