抽奖权重算法

算法实现

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;
}
上一篇:DataFrame 中括号取数据用法


下一篇:文章按给定权重、生成时间综合排序