Loading

抽奖权重算法

算法实现

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;
}
posted @ 2020-11-26 19:59  Jansang  阅读(973)  评论(0)    收藏  举报