php - 从数组中选择五个唯一的随机 PHP 值并将它们放入单独的变量中
问题描述
我有一个数组,例如:
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;
}
解决方案
推荐阅读
- python - Statsmodels (Patsy) 非法变量名/“系列”对象不可调用错误
- node.js - 发送“画布”生成的图像,而不将其保存到文件中
- r - dplyr 在列范围内发生变异
- ios - 打开 UIDocument 时如何显示错误消息?
- python - 我想在 Python 的 if 语句中有多个值
- mysql - JOIN SQL 结果来自同一表的一行并使用值作为列名
- nsdictionary - NSDictionary - 无法识别的选择器发送到实例 - 错误
- java - Moshi 找不到我用 Kotlin 编写的用于参数化类型的自定义适配器
- javascript - 如何在 JavaScript 中调用另一个对象的函数?
- php - Laravel 5中的子关系?