-1

好吧,我对 rand() 有用;我需要从 1 到 x 数量 4 次,并确保该值不会返回。

这是我的代码:

 $Count = 15;
 $secondstage = '';
 $arrayindex = '';
 for($i=1; $i<5; $i++){
    $arrayindex = rand(1,$Count);
    if($secondstage == $arrayindex){
        for($b=1; $arrayindex == $secondstage; $b++){
            $arrayindex = rand(1,$Count);
        }
    }
    $secondstage = $arrayindex;
    echo $secondstage;
    echo '<br>';
 }

我在这里有一些逻辑错误吗?我想也许使用 while 但 for 也应该工作。

4

4 回答 4

2

所以基本上你想要4个1到15之间的随机非重复数字,包括在内?您为此使用了太多代码。一个更简单的版本:

$numbers = array();
do {
   $possible = rand(1,15);
   if (!isset($numbers[$possible])) {
      $numbers[$possible] = true;
   }
} while (count($numbers) < 4);
print_r(array_keys($numbers));
于 2012-08-04T00:38:12.663 回答
1

我会将已经随机的数字放入一个数组中:

<?php 
$count = 15;
$cArray = array();
for($i=1; $i<5; $i++){
    $rand = rand(1, $count);
    if(in_array($rand, $cArray)){
        $i--;
    } else {
        $cArray[] = $rand;
        echo $rand . "<br>";
    }
   }
?>

我检查了一下,这段代码在本地服务器上工作:)

于 2012-08-04T00:48:32.677 回答
1
$count = 15;
$values = range(1, $count);
shuffle($values);
$values = array_slice($values, 0, 4);
于 2012-08-04T02:43:03.050 回答
0

你可以这样做(这会给你一个带有原始数组随机键的数组):

<?php

$array = array();
$max = 100;
$numberValuesWanted = 5;

for($i = 0; $i < $max; $i++)
  $array[] = $i;

$randomKeys = array_rand($array, $numberValuesWanted);

print_r($randomKeys);
于 2012-08-04T00:37:30.217 回答