循环PHP中的随机数组



目前正在开发一个.比方说随机字生成器。我想我已经让它工作了,但不幸的是,for循环返回的值与第一个相同。

`

$ones = array("One.", "Two.", "Three.", "Four.", "Five.", "Six.", "Seven.", "Eight.", "Nine.", "Ten.");
$one_rand = array_rand($ones, 2);
$one = $ones[$one_rand[0]];
$twos = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10");
$two_rand = array_rand($twos, 2);
$two = $twos[$two_rand[0]];
$ends = array(".a", ".b", ".c", ".d", ".e", ".g", ".h", ".i", ".j");
$end_rand = array_rand($ends, 2);
$end = $ends[$end_rand[0]];

$return = $one . $two . $end;

for ($x = 1; $x <= 5; $x++) {
echo $return . "<br>";
}

`

此代码返回(例如(:

Three.4.b <br>
Three.4.b <br>
Three.4.b <br>
Three.4.b <br>
Three.4.b <br>

但我希望它在每次" < br > "之后都是随机的。

提前谢谢。

所以问题是您将值分配给$1、$2、$3一次,这意味着在那之后创建循环时它不会改变,您需要做的是循环值分配,比如:

$ones = array("One.", "Two.", "Three.", "Four.", "Five.", "Six.", "Seven.", "Eight.", "Nine.", "Ten.");
$twos = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10");
$ends = array(".a", ".b", ".c", ".d", ".e", ".g", ".h", ".i", ".j");
for ($x = 1; $x <= 5; $x++) {
$one_rand = array_rand($ones, 2);
$one = $ones[$one_rand[0]];
$two_rand = array_rand($twos, 2);
$two = $twos[$two_rand[0]];
$end_rand = array_rand($ends, 2);
$end = $ends[$end_rand[0]];
$return = $one . $two . $end;
echo $return . "<br>";
}

但这意味着你需要为每个循环调用array_rand,这很糟糕,更好的选择是先随机化数组,然后你可以使用循环索引来选择值,这仍然是随机的,但更快,比如:

$ones = array("One.", "Two.", "Three.", "Four.", "Five.", "Six.", "Seven.", "Eight.", "Nine.", "Ten.");
$twos = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10");
$ends = array(".a", ".b", ".c", ".d", ".e", ".g", ".h", ".i", ".j");
// I have used shuffle instead of array_rand, because for array_rand you 
// need to specify the number of items returned, which is not really dynamic
shuffle($ones);
shuffle($twos);
shuffle($ends);
for ($x = 1; $x <= 5; $x++) {
echo $ones[$x] . $two[$x] . $end[$x] . "<br>";
}

最新更新