我需要创建两个数组,用于模拟乐透彩票的开奖。
第一个数组将由1到49之间的6个唯一数字组成。第二个数组将由1到49之间的7个唯一数字组成。
我对PHP还是很陌生,我不知道如何填充数组,给它指定预定义的大小,将1到49之间的六个数字随机放入数组中,然后最后以升序对数组进行排序。
这是我的快速草稿,我认为这朝着正确的方向前进?
$tmp;
$lotto = array(rand(1,49)); //Creating the random number for $lotto
$lottoMax = array(rand(1,49)); //Creating the random number for $lottoMax
for($tmp=0; $lotto <= 6; $tmp++){
//creating the size of the array?
}
任何建议/技巧/帮助将不胜感激!谢谢你。
有几种方法可以解决这种问题。首先想到的是,首先使用创建数字1-49的数组range(1, 49)
。然后使用随机排列数组,shuffle()
以便其顺序随机化。最后,由于它已经被随机化了,因此您可以将前6或7个数字切掉以填充两个数组(我将使用array_slice()
)。保证内容没有重复,并且只需要执行几次操作即可。
// The bag of numbers is a range
$bag = range(1, 49);
// Shuffle it
shuffle($bag);
// Get the first array
$first_group = array_slice($bag, 0, 6);
// Shuffle it again and get the second array
shuffle($bag);
$second_group = array_slice($bag, 0, 7);
print_r($first_group);
Array
(
[0] => 36
[1] => 22
[2] => 34
[3] => 17
[4] => 23
[5] => 25
)
print_r($second_group);
Array
(
[0] => 40
[1] => 32
[2] => 33
[3] => 36
[4] => 29
[5] => 7
[6] => 3
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句