适用于抽奖、随机广告等需要按概率从一组数据中取出一个的场景。

    代码实例:

    1. function getProbabilityPrizeId($prize_info)
    2. {
    3. $prize_arr = [];
    4. foreach ($prize_info as $key => $val) {
    5. $prize_arr[$val['id']] = bcmul($val['probability'], '1000', 0);
    6. }
    7. //概率数组的总概率精度
    8. $proSum = array_sum($prize_arr);
    9. //概率数组循环
    10. $randNum = mt_rand(1, $proSum);
    11. foreach ($prize_arr as $key => $proCur) {
    12. $randNum -= $proCur;
    13. if ($randNum <= 0) {
    14. $prizeId = $key;
    15. break;
    16. }
    17. }
    18. return $prizeId;
    19. }
    20. $prize_arr = [
    21. ['id' => 1, 'prize' => '平板电脑', 'probability' => 1],
    22. ['id' => 2, 'prize' => '数码相机', 'probability' => 5],
    23. ['id' => 3, 'prize' => '音箱设备', 'probability' => 10],
    24. ['id' => 4, 'prize' => '4G优盘', 'probability' => 12],
    25. ['id' => 5, 'prize' => '10Q币', 'probability' => 22],
    26. ['id' => 6, 'prize' => '下次没准就能中哦', 'probability' => 50],
    27. ];
    28. var_dump(getProbabilityPrizeId($prize_arr));