简体   繁体   English

for循环中的随机数组PHP

[英]random array in for loop PHP

Currently working on a.. lets say random word generator.目前正在研究一个..让我们说随机词生成器。 I think I made it already work, but unfortunately for loop returns the same value as the first one.我想我已经让它工作了,但不幸的是 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>";
}

` `

This code returns(for example):此代码返回(例如):

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

But I want it to be random after every " < br > ".但我希望它在每个“ < br > ”之后都是随机的。

Thank you in advance.先感谢您。

so the issue is that you assign the values to $one, $two, $three once, that means it will not change when you create a loop after that, what you need to do is loop the value assignment something like:所以问题是您将值分配给 $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>";
}

But that means you will need to call array_rand for each loop, which is pretty bad, a better choice would be to just randomize the array first and then you can use the loop index to choose the values, which will still be random but faster, something like:但这意味着您需要为每个循环调用 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