抽獎權重算法


算法實現

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