繁体   English   中英

for循环中的随机数组PHP

[英]random array in for loop 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>";
}

`

此代码返回(例如):

三.4.b
三.4.b
三.4.b
三.4.b
三.4.b

但我希望它在每个“ < br > ”之后都是随机的。

先感谢您。

所以问题是您将值分配给 $one, $two, $three 一次,这意味着在之后创建循环时它不会改变,您需要做的是循环值分配,例如:

$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>";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM