<?php

namespace Common\Helper;

class PrizeHelper
{
    /**
     * 抽取礼物
     * $weight_list = [
     *       [
     *           'id' => 1,
     *           'name' => '手机',
     *           'weight' => 100
     *       ],
     *       [
     *           'id' => 2,
     *           'name' => '电脑',
     *           'weight' => 100
     *       ],
     *       [
     *           'id' => 3,
     *           'name' => '洗衣机',
     *           'weight' => 100
     *       ],
     *   ];
     * 
     */
    public static  function getPrize($weight_list)
    {
        foreach ($weight_list as $gv) {
            $giftWeightArr[$gv['id']] = $gv['weight'];
        }

        $result = '';
        //概率数组的总概率精度
        $sumWeight = array_sum($giftWeightArr); //计算数组中元素的和
        $luckyNum = mt_rand(1, $sumWeight);
        //概率数组循环
        $beginCursor = $endCursor = 0;
        foreach ($giftWeightArr as $id => $weight) {
            $beginCursor = $endCursor;
            $endCursor += $weight;

            if ($luckyNum > $beginCursor && $luckyNum <= $endCursor) {
                $result = $id;
                break;
            }
        }
        return $result;
    }

    // 获取概率
    public static function getFixRand($weight)
    {
        if ((int)$weight < 0 || (int)$weight > 100) {
            return -1;
        }

        $weightArr = [
            1 => $weight,
            2 => 100 - $weight,
        ];

        $result = '';

        //概率数组的总概率精度
        $sumWeight = array_sum($weightArr); //计算数组中元素的和
        $luckyNum = mt_rand(1, $sumWeight);
        //概率数组循环
        $beginCursor = $endCursor = 0;
        foreach ($weightArr as $id => $w) {
            $beginCursor = $endCursor;
            $endCursor += $w;

            if ($luckyNum > $beginCursor && $luckyNum <= $endCursor) {
                $result = $id;
                break;
            }
        }
        if ($result == 1) {
            return true;
        } else {
            return false;
        }
    }
}

这两个函数比较常用,一个是根据概率来看是否中奖。另一个是中了什么奖。