簡體   English   中英

PHP rand 查詢結果 - 檢查新的隨機查詢與之前的不一樣

[英]PHP rand query results - check so the new randomized query is not the same as previous

我的 PHP 代碼現在看起來像這樣:

$query = mysql_query("SELECT * FROM `questions` WHERE `id` = '$id' ORDER BY RAND()") or die(mysql_error());
$cmd = mysql_fetch_assoc($query);

$question = $cmd['question'];

現在,問題只是隨機化的——這很好——但有時同樣的問題會再次出現,我不希望這樣。 我假設您可以使用 session 解決此問題。 但是怎么做? 如果有人可以修復代碼,我將不勝感激。

也許是這樣的:

$query = "SELECT * FROM `questions` WHERE `id` = `$id` AND `id` NOT IN (";
$query .= implode(', ', array_keys($_SESSION['questions']));
$query .= ') ORDER BY RAND()';
mysql_query($query) or die(mysql_error());

// Here add the returned questions to the $_SESSION['questions'] array so they would not appear again.

我不知道該程序的 rest 是如何工作的,因此您需要的邏輯可能會有所不同,但我確信您正在尋找這種查詢。

這應該做你需要的:

$query = mysql_query("SELECT * FROM `questions` WHERE `id` = '$id' ORDER BY RAND()") or die(mysql_error());
$question = null;
while ($cmd = mysql_fetch_assoc($query)) {
    if (array_search($cmd['question'], $_SESSION['asked']))
        continue;
    $question = $cmd['question'];
    $_SESSION['asked'][] = $question;
    break;
}
if (!$question) {
    // No unique questions found.
} else {
    // $question will be unique here
}

您可以在 session 中存儲所有之前提出的問題的 ID:

if (!isset($_SESSION['QuestionAsked']))
{
    $_SESSION['QuestionAsked'] = array();
}

然后,您可以擴展查詢以排除所有問到的問題:

$query = 'SELECT * FROM `questions`';
if ($_SESSION['QuestionAsked'])
{
    $askedIds = implode(',', $_SESSION['QuestionAsked']);
    $query .= sprintf(' WHERE `id` NOT IN (%s)', $askedIds);
}
$query .= ' ORDER BY RAND()';

最后在查詢一個新問題后,將其添加到 session 中:

$_SESSION['QuestionAsked'][] = $currentQuestionId;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM