PHP教程

php大转盘算法

本文主要是介绍php大转盘算法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
// 获取中间记录的id
function get_rand() {
    $arr = [
        '0'=>['id'=>1,'name'=>'test1','rand'=>0],
        '1'=>['id'=>2,'name'=>'test2','rand'=>1],
        '2'=>['id'=>3,'name'=>'test3','rand'=>2],
        '3'=>['id'=>4,'name'=>'test4','rand'=>1],
        '4'=>['id'=>5,'name'=>'test5','rand'=>2],
        '5'=>['id'=>6,'name'=>'test6','rand'=>6]
    ];
    $result = false;
    $all_rand = 0;
    foreach ($arr as $v) {
        $all_rand +=$v['rand'];
    }
    foreach ($arr as $key=>$value) {
        if ($value['rand']>0) {
            $pro = $value['rand'];
            $randNum = mt_rand(1,$all_rand);
            if ($randNum<=$pro) {
                $result = $value['id'];
                break;
            } else {
                $all_rand -= $pro;
            }
        }
    }
    return $result;
}
echo get_rand();
这篇关于php大转盘算法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!