0

我试图从一个数字数组中显示 10 个随机数,但没有成功。

这是我的代码:

<?php
$num = array("2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009");

//echo $num[rand(0,9)];
echo '<br/>';
for ($num = 2000; $num <= 10; $num[rand(0,9)]++)
{
    echo "The number is " . $num . "<br />";
}
?>

display_errors = On尽管我的 ubuntu php.ini 上有脚本,但该脚本没有显示任何内容。

我哪里错了?

4

6 回答 6

3

只需使用array_rand

array_rand($num, 10); // returns a new array with 10 randomly selected values.

之后,您可以使用以下方法迭代这些foreach

$rand = array_rand($num, 10);

foreach($rand as $key) {
  echo "The number is " . $num[key] . "<br />";
}
于 2012-11-13T10:26:18.717 回答
3

我会改用shuffle函数。

<?php
$num = array("2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009");
shuffle($num);
echo '<br/>';
foreach ($num as $value)
  {
  echo "The number is " . $value . "<br />";
  }
?>
于 2012-11-13T10:29:19.083 回答
1

尝试洗牌()

$num= array("2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", 
  "2009");

shuffle($num);

 //echo $num[rand(0,9)];
 echo '<br/>';
 for ($i = 0; $i < count($num); $i++)
 {
  echo "The number is " . $num[$i] . "<br />";
 }
于 2012-11-13T10:29:30.730 回答
0

您从 开始循环$num = 2000并在$num <= 10. 所以它不执行。

于 2012-11-13T10:27:36.827 回答
0
<?php
  $num= array("2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", 
  "2009");

 //echo $num[rand(0,9)];
 echo '<br/>';
 for ($i = 0; $i < count($num); $i++)
 {
  echo "The number is " . $num[rand(0, count($num))] . "<br />";
 }
?>
于 2012-11-13T10:28:30.517 回答
0
    $num= array("2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009");

    for($i=0; $i<10; $i++){
        $rand = rand(0,count($num));
        echo "The number is " . $num[$rand] . "<br />";

        // unset($num[$rand]); //to get unique numbers each time .. this will unset array item after its showed
        // $num = array_values($num); //reindex after unset
    }

如果您只想获得唯一的结果,可以使用 unset 和 array_values

于 2012-11-13T10:32:25.747 回答