我即将创建一个脚本,为我的彩票选择一个赢家.门票的数量选择如下:金额* 100所以$1.26 = 126门票.
我做了这个,它给了我中奖的票号,但后来我无法得到获胜的用户:
$totaltickets = 0; foreach($players as $player){ $totaltickets += $player->depositedValue*100; } $winningTicket = rand(1,$totaltickets);
我有这样的行:
Player1 - 1.25$ Player2 - 5.99$ etc..
如果有可能那么我想保持这样,并且每个票证在数据库中没有1000行.
我正在考虑保持你对数字的想法而不是引入一个数组.
我将让球员保持他们的门票位置(开始/结束).当我选择随机票时,我会看看我的号码是否在他们的范围内,如果是,那么我找到了胜利者.
<?PHP class TicketMaster { private $players = array(); public $total = 0; public function addPlayer($player) { $player->tickets[0] = $this->total; $this->total += $player->value; $player->tickets[1] = $this->total; $this->players[] = $player; } public function selectWinner() { $ticket = rand(0,$this->total); foreach ($this->players as $player) if ($ticket >= $player->tickets[0] && $ticket <= $player->tickets[1]) return $player; return false; } } class Player { public $name = ''; public $value = 0; public $tickets = array(0,0); function __construct($name,$value) { $this->name = $name; $this->value = $value; } } $ticketMaster = new TicketMaster(); $ticketMaster->addPlayer(new Player("John",200)); $ticketMaster->addPlayer(new Player("Mike",200)); $ticketMaster->addPlayer(new Player("Dave",1000)); echo $ticketMaster->selectWinner()->name;
也
$ticket = rand(0,$this->total); //change to random_int,but I kept it at rand because eval.in only works with this one
Output:戴夫
戴夫大部分时间都赢了,因为他有1000张门票,而其他两位只有400张门票的球员.