我有一个数组,例如:
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;
}
答案 0 :(得分:7)
您可以shuffle
数组并使用list
分配值
$arr = array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");
shuffle( $arr );
list($one, $two, $three, $four, $five) = $arr;
答案 1 :(得分:1)
使用此:
$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);
<强>输出强>
array(5) {
[0]=>
string(3) "ggg"
[1]=>
string(3) "fff"
[2]=>
string(3) "eee"
[3]=>
string(3) "ddd"
[4]=>
string(3) "ccc"
}
直播示例
答案 2 :(得分:0)
这应该有效:
$arr = array("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");
$tmp = $arr;
array_rand($tmp);
$one = $tmp[0];
$two = $tmp[1];
...
记住,如果$ tmp [n]中的值实际存在
,它将不会显示答案 3 :(得分:0)
您可以使用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...