首页 > 代码库 > 概率中奖

概率中奖

<?php
    /**
     * [gailv description]
     * @param array $data
     * @return int $result 正确返回中奖ID 错误就返回0
     */
    function probability($data)
    {
        if (!is_array($data) || empty($data)) {
            return 0;
        }

        $result = 0;

        //概率和
        $probabilitySum = array_sum($data);

        foreach ($data as $key => $value) {
            $rand = mt_rand(1, $probabilitySum);
            if ($rand <= $value) {
                $result = $key;
            }else{
                $probabilitySum -= $value;
            }
        }

        return $result;
    }

    $data = array(
        1 => 10,
        2 => 30,
        3 => 40,
        4 => 90,
        10 => 100
    );

    var_dump(probability($data));


    

 

概率中奖