我有一个数组,例如:
array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");
我想从中选择五个随机和唯一值,并将它们放入五个不同的变量中,例如:
$one = "ccc";
$two = "aaa";
$three = "bbb";
$four = "ggg";
$five = "ddd";
我已经在下面找到了这段代码,它适用于生成随机字符串并仅显示它们,但我想要的输出是将它们放入不同的变量中并能够单独使用它们。
<?php
$arr = $arr_history = array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");
for ( $i = 1; $i < 5; $i++ )
{
// If the history array is empty, re-populate it.
if ( empty($arr_history) )
$arr_history = $arr;
// Randomize the array.
array_rand($arr_history);
// Select the last value from the array.
$selected = array_pop($arr_history);
// Echo the selected value.
echo $selected . PHP_EOL;
}
您可以shuffle
数组并使用list
来分配值
$arr = array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");
shuffle( $arr );
list($one, $two, $three, $four, $five) = $arr;
文档: shuffle((, list((
使用这个:
$arr = $arr_history = array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");
$random = [];
for ( $i = 1; $i <= 5; $i++ )
{
// If the history array is empty, re-populate it.
if ( empty($arr_history) )
$arr_history = $arr;
// Randomize the array.
array_rand($arr_history);
// Select the last value from the array.
$selected = array_pop($arr_history);
array_push($random, $selected);
}
var_dump($random);
- 我已经修复了您的循环逻辑,因此它现在显示 5 个项目而不是 4 个项目。
- 我正在使用简短的语法来定义需要 5.4 或更高版本的数组。
输出
array(5) {
[0]=>
string(3) "ggg"
[1]=>
string(3) "fff"
[2]=>
string(3) "eee"
[3]=>
string(3) "ddd"
[4]=>
string(3) "ccc"
}
现场示例
代表
这应该有效:
$arr = array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");
$tmp = $arr;
array_rand($tmp);
$one = $tmp[0];
$two = $tmp[1];
...
虽然 $tmp[n] 中的值确实存在,但它不会
您可以使用 PHP 的shuffle
函数来随机化数组中元素的顺序,然后获取第一个元素。
$randomArray = array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");
shuffle($randomArray);
$randomArray = array_slice($randomArray, 0, 5);
$randomArray[0]; //1st element
$randomArray[1]; //2nd element
$randomArray[2]; //3rd element...