如何以随机顺序显示内容?

时间:2013-02-07 04:48:24

标签: php mysqli

使用下面的代码我将显示从数据库中检索到的问题:

    $qandaquery = "SELECT q.QuestionId, q.QuestionNo, q.QuestionContent
                    FROM Question q
                    WHERE SessionId = ?
                    GROUP BY q.QuestionId
                    ORDER BY q.QuestionId";

    $qandaqrystmt=$mysqli->prepare($qandaquery);
    // You only need to call bind_param once
    $qandaqrystmt->bind_param("i",$session);
    // get result and assign variables (prefix with db)
    $qandaqrystmt->execute(); 
    $qandaqrystmt->bind_result($qandaQuestionId,$qandaQuestionNo,$qandaQuestionContent);

    $arrQuestionId = array();
    $arrQuestionNo = array();
    $arrQuestionContent = array();


    while ($qandaqrystmt->fetch()) {
    $arrQuestionId[ $qandaQuestionId ] = $qandaQuestionId;
    $arrQuestionNo[ $qandaQuestionId ] = $qandaQuestionNo;
    $arrQuestionContent[ $qandaQuestionId ] = $qandaQuestionContent;

  }

    $qandaqrystmt->close();


foreach ($arrQuestionId as $key=>$question) {

?>

<div class='lt-container'>
<p><strong>QUESTION <span id="quesnum"></span>:</strong></p>
<p><?php echo htmlspecialchars($arrQuestionNo[$key]) . ": " .  htmlspecialchars($arrQuestionContent[$key]); ?></p>
</div>


<?php

}

?>

现在它在哪里说QUESTION

<p><strong>QUESTION # <?php echo $q; ?> :</strong></p> <?php $q++; ?>

我想要保持同一个地方

但它显示问题详情:

<p><?php echo htmlspecialchars($arrQuestionNo[$key]) . ": " .  htmlspecialchars($arrQuestionContent[$key]); ?></p>

我希望它以RANDOM顺序显示问题。例如,如果我有以下3个问题:

QUESTION 1:

1. What is 2+2?

QUESTION 2:

2. What is 3+3?

QUESTION 3:

3. What is 4+4?

它可以按此顺序显示为一个例子:

QUESTION 1:

2. What is 3+3?

QUESTION 2:

3. What is 4+4?

QUESTION 3:

1. What is 2+2?

3 个答案:

答案 0 :(得分:0)

而不是ORDER BY q.QuestionId使用ORDER BY RAND()

答案 1 :(得分:0)

shuffle()函数随机化数组中元素的顺序。 Read more

示例

<?php
$my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse");

shuffle($my_array);
print_r($my_array);
?>

rray ( [0] => Cat [1] => Horse [2] => Dog )

答案 2 :(得分:0)

mysql rand()函数怎么样,例如

$qandaquery = "SELECT rand() as pos, q.QuestionId, q.QuestionNo, q.QuestionContent
                    FROM Question q
                    WHERE SessionId = ?
                    GROUP BY q.QuestionId
                    order by pos";
相关问题