php - 如何配置 php 的 "array_rand"不连续给出 2 个相同的结果?

标签 php arrays random

我使用 php array_rand 从数组中选择 1 个随机记录,示例:

$style_class = array("st_style1","st_style2","st_style3","st_style4");
$random_class = array_rand($style_class, 1);
$div_class = $style_class[$random_class];

问题是有时它会多次给出相同的记录,而由于我只使用 4 条记录,它经常安静地发生(不需要使用“array_rand”)。

例子:

st_style1, st_style2, st_style2, st_style2, st_style4, st_style2 ...

有没有办法解决这个问题,让两条相同的记录不会连续显示两次。

例如

st_style2, st_style4, st_style2, st_style1, st_style3, st_style2, st_style1 ...

最佳答案

最简单的解决方案是跟踪最新的一个并继续随机调用直到你得到不同的东西。像这样的东西:

$style_class = array("st_style1","st_style2","st_style3","st_style4");
$styles = array()
$lastStyle = -1
for($i = 0; $i < 5; $i++) {
    while(1==1) {
        $newStyle = array_rand($style_class, 1);
        if ($lastStyle != $newStyle) { 
            $lastStyle = $newStyle;
            break;
        }
    }
    $div_class = $style_class[$lastStyle]
    $styles[] = $div_class
}

然后按顺序使用$styles[]数组。它不应该有任何重复

关于php - 如何配置 php 的 "array_rand"不连续给出 2 个相同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7839264/

相关文章:

openssl - php.ini 文件 - openssl

php - Laravel 5 覆盖summernote 图片上传

c++ - 使用排序函数 C++ 对 char 数组进行排序

javascript - 我可以使用哪些方法来操作对象中数组的数据? (仅限伪代码)

php - 比较从表中获取的数据时出错

php - 如何使用 PHP 生成随机的 DARK 十六进制颜色代码?

java - 为什么平均值与原始权重不太接近?

php - 内存不足,Mysql_query() 无法保存结果集

选择后立即删除 PHP

swift - 如何在 Swift 中生成大范围的随机数?