下面是一个简单的PHP函数,用于抽奖:
function lottery($prizes) { $totalWeight = 0; foreach ($prizes as $prize) { $totalWeight += $prize['weight']; } $randomNumber = mt_rand(1, $totalWeight); $currentWeight = 0; foreach ($prizes as $prize) { $currentWeight += $prize['weight']; if ($randomNumber <= $currentWeight) { return $prize['name']; } } return null; }
使用方法:
$prizes = array( array('name' => '奖品1', 'weight' => 100), array('name' => '奖品2', 'weight' => 200), array('name' => '奖品3', 'weight' => 300), array('name' => '奖品4', 'weight' => 400) ); $winner = lottery($prizes); echo '恭喜您获得了:' . $winner;
其中,$prizes是一个二维数组,每个元素包含一个奖品的名称和权重。函数会根据每个奖品的权重计算总权重,然后生成一个1到总权重之间的随机数。接着,函数会
遍历每个奖品,累加它们的权重,直到当前权重大于等于随机数。此时,函数会返回对应的奖品名称。如果遍历完所有奖品都没有找到合适的奖品,函数会返回null。