首页 > 解决方案 > 无重复的 PHP 随机数组

问题描述

当我重新加载浏览器时,我试图做正确的事情,数组随机变化而没有重复。当我重新加载浏览器时,我看到重复的数组随机出现,请帮助我。

这是代码

<html>
    <head></head>
    <body>
        <?php


        $size = 3; $strl = "what"; $fitness1 = array("steps $strl", "dizziness $strl", "$strl symptoms  ", "treatment $strl", "obesity $strl","$strl discharge");

        $fitness1 = array_unique($fitness1);

        $number = 1;

        for ($b = 0; $b < $size ;$b++){


           echo $number++ . "<table><tr><td> " . $fitness1[array_rand($fitness1)] . "<td></tr></table>";echo $number++ . "<table><tr><td> " . $fitness1[array_rand($fitness1)] . "<td></tr></table>";




    for ($i = 0; $i < $size; $i++){



        }
    } 

        ?>
    </body>
</html>

标签: php

解决方案


$i = 0;
$number = 1;
do {
    shuffle($fitness1);
    echo "<tr><td>" . ($number++) ."</td><td>" . array_shift($fitness1) ."</td></tr>";
    echo "<tr><td>" . ($number++) ."</td><td>" . array_shift($fitness1) ."</td></tr>";
    $i++;
} while ($i < $size && !empty($fitness1));

shuffle()这个函数洗牌(随机化元素的顺序)一个数组 Blockquote

所以每次重新加载页面,顺序都会不同

https://www.php.net/manual/en/function.shuffle.php

array_shift()将数组的第一个值移开并返回,将数组缩短一个。

https://www.php.net/manual/en/function.array-shift.php

打印值后,它将从数组中删除。所以没有重复的值


推荐阅读