抽奖权重计算

        header('Content-type:text/html;charset=utf-8');
    $data=array(
    0=>array('id'=>1,'name'=>'一等奖','weight'=>'5'),
    1=>array('id'=>2,'name'=>'二等奖','weight'=>'10'),
    2=>array('id'=>3,'name'=>'三等奖','weight'=>'25'),
    3=>array('id'=>4,'name'=>'谢谢抽奖','weight'=>'60')
    );


    // 权重数值越高,被返回的概率越大
    function countWeight($data){
        $weight=0;
        $temp=array();
        foreach($data as $v){
            $weight+=$v['weight'];
            for($i=0;$i<$v['weight'];$i++){
                $temp[]=$v;//放大数组
            }
        }
        $int=mt_rand(0,$weight-1);//获取一个随机数
        $result=$temp[$int];
        return $result;
    }            

测试

$id0 = 0;
    $id1 = 0;
    $id2 = 0;
    $id3 = 0;
    for($i=1;$i<=100;$i++){
        $r = countWeight($data);
        switch($r['id']){
            case 1:
                $id0++;
                break;
            case 2:
                $id1++;
                break;
            case 3:
                $id2++;
                break;
            case 4:
                $id3++;
                break;
        }
    }


    d($r);
    d($id0);
    d($id1);
    d($id2);
    d($id3);
    
    
    //打印数组
    function d($data , $isexit = 0){
        echo '<pre>';
        var_dump($data);
        echo '</pre>';
        if ($isexit) exit();
    }

 

posted @ 2015-04-22 17:51  壁虎漫步.  阅读(1533)  评论(0编辑  收藏  举报