php语法如何实现概率抽奖功能?
如何php语法做一个概率抽奖功能?下面编程教程网小编给大家简单介绍以下具体实现代码!
具体代码如下:
<?php
$prize = [
['name' => 'iphone13', 'chance' => 100],
['name' => '佳能相机', 'chance' => 900],
['name' => '洗碗机', 'chance' => 1000],
['name' => '加班一天', 'chance' => 2000],
['name' => '谢谢参与', 'chance' => 3000]
];
// 概率重组
$chance = 0;
foreach ($prize as &$item) {
$chance += $item['chance'];
$item['chance'] = $chance;
}
// 随机抽奖
$rand = mt_rand(1, 10000);
$result = [];
foreach ($prize as $_k => $_v) {
if ($_k == 0) {
if ($rand > 0 && $rand <= $_v['chance']) {
$result = $_v;
break;
}
} else {
if ($rand > $prize[$_k - 1]['chance'] && $rand <= $_v['chance']) {
$result = $_v;
break;
}
}
}
// 抽奖结果
echo json_encode(compact('rand', 'result'));
以上是编程学习网小编为您介绍的“php语法如何实现概率抽奖功能?”的全面内容,想了解更多关于 php入门 内容,请继续关注编程基础学习网。