抽奖权重算法


算法实现

public function caleResult()
{
    $data = [
        ['id' => 1, 'name' => '一等奖', 'weight' => 5],
        ['id' => 2, 'name' => '二等奖', 'weight' => 10],
        ['id' => 3, 'name' => '三等奖', 'weight' => 25],
        ['id' => 4, 'name' => '四等奖', 'weight' => 60],
    ];

    //计算总权重
    $total = 0;
    foreach ($data as $val) {
        $total += $val['weight'];
    }

    $rate   = 0;
    $result = [];
    $random = mt_rand(1, $total);
    foreach ($data as $val) {
        $rate += $val['weight'];
        if ($random > $rate) {
            continue;
        }
        $result = $val;
    }
    return $result;
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM