抽奖权重计算

        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();
    }

 

转载于:https://www.cnblogs.com/phpfensi/p/4448209.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值