2

我正在尝试为自己的娱乐构建一个简单的彩票号码生成器。我必须在 1 和 49 之间选择六个数字,显然没有重复。

我已经尝试将这个mt_rand功能用于六个不同的变量,然后按顺序呼应它们,但我想可能存在重复数字。所以现在我正试图让以下工作。

<?php 
$randomString = substr(shuffle("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49"), 0, 6); echo $randomString; 
?>

我知道 substr 用于字符串而不是数组,但我找不到替代方法。

有人有解决方案吗?

4

5 回答 5

4

您可以使用array_slice从数组中获取 6 个数字:

<?php
$numbers = range(1, 49);
shuffle($numbers);
$numbers = array_slice($numbers, 0, 6);
print_r($numbers);
?>
于 2013-08-17T22:01:56.367 回答
1

这可以使用下面的一些代码range()shuffle()函数来实现。


function num_rand($min, $max, $val) {
   $range = range($min, $max);
   shuffle($range);
   $result = array_slice($range, 0, $val);

      foreach($result as $number) {
         $number_string .= $number . ', ';
      }

   return rtrim($number_string, ', ');
}


echo num_rand('1', '49', '6');
于 2013-08-17T23:01:23.037 回答
1

array_rand基本上是为此而设计的,但请记住,它返回的是,而不是值。

所以试试这个:

$numbers = array_rand(array_flip(range(1,49)),6);
var_dump($numbers);
于 2013-08-17T22:04:10.390 回答
1

更好的做法是从 1 到 49 只获得 6 个不同的随机数

numbers = array();
for(i=1;i<=6;i++){
    do{
        pick = rand(1,49);
    }while (in_array(pick, numbers));
    numbers[] = pick;
}
于 2013-08-17T22:36:09.803 回答
0

您还可以随机 6 个数字并检查是否没有重复这样的:

<?php
srand();
$TOTAL = 6;
$MAX = 46;
$MIN = 1;

$numbers = array();
for($i = 0; $i < $TOTAL; $i++) {
do {
    $new_number = rand($MIN,$MAX);
}
while(in_array($new_number, $numbers));

echo $new_number . "<br>";
}
?>

对我来说,这是最直接的解决方案,但我不知道它是否是最好的解决方案。

于 2013-08-17T22:32:58.180 回答