php按指定概率获得key

简介

php按指定概率获得key

<?php
function getkey()
{
    $pro = [
        'key1' =>80, //80%出现概率
        'key2' =>20, //20%出现概率
    ];

    $ret = '';
    $sum = array_sum($pro);
    foreach($pro as $k=>$v)
    {
        $r = mt_rand(1, $sum);
        if($r <= $v)
        {
            $ret = $k;
            break;
        }else{
            $sum = max(0, $sum - $v);
        }
    }
    return $ret;
}

echo getkey();