php按照奖品百分比随机抽奖代码分析
程序员文章站
2022-05-25 18:14:45
...
/** * 概率算法 * @param array $probability * @return integer|string */ function get_rand($probability) { // 概率数组的总概率精度 $max = array_sum($probability); foreach ($probability as $key => $val) { $rand_number = mt_rand(1, $max);//从1到max中随机一个值 if ($rand_number "平板电脑", "prob" => 1 ), array( "prize" => "数码相机", "prob" => 3 ), array( "prize" => "音箱设备", "prob" => 5 ), array( "prize" => "8G优盘", "prob" => 20 ), array( "prize" => "10Q币", "prob" => 200 ), array( "prize" => "下次没准就能中噢", "prob" => 771 ) ); foreach ($data as $key => $val) { $probability[$key] = $val["prob"]; } $n = get_rand($probability); $res['yes'] = $data[$n]["prize"];//$res['yes'] =$data[$n][0]; unset($data[$n]); // 将中奖项从数组中剔除,剩下未中奖项 shuffle($data); // 将其它奖项顺序打乱 $func = create_function('$x', 'return $x["prize"];'); //$res['no'] = array_map(function($x){return $x[0];}, $data); // 除了中奖外的其他数据 $res['no'] = array_map($func, $data); // 除了中奖外的其他数据 print_r($res);