如何在 PHP 中显示随机结果


How To Display Random Results in PHP

我试图显示来自文本文件的 2 个或更多个唯一的随机结果,请问我该怎么做?

但我需要独特的结果,而不是 2 个或更多相同的结果。

当前使用此代码,但它只返回 1 个随机结果:

<?php
$text = file_get_contents('flatFileDB.txt');
$textArray = explode("'n", $text);
$randArrayIndexNum = array_rand($textArray);
$randPhrase = $textArray[$randArrayIndexNum];
?>
<?php echo $randPhrase ?>

我会使用类似的东西

shuffle($textArray);
    echo $textArray[0];
    echo $textArray[1];

http://php.net/manual/tr/function.shuffle.php

你也可以试

一试。代码未经过测试。我正在将用过的收集到一个数组中,并检查,以前用过的。

$text = file_get_contents('flatFileDB.txt');
$textArray = explode("'n", $text);
$used = array();
$countOfRandoms = 2;
$randoms = array();
$i = 1;
do {
    if ($countOfRandoms == $i) {
        break;
    }
    $randArrayIndexNum = array_rand($textArray);
    if (in_array($randArrayIndexNum, $used)) {
        continue;
    }
    $used[]  = $randArrayIndexNum;
    $random = $textArray[$randArrayIndexNum];
    $i++;
} while (true);