php仅从mysql检索随机行一次

标签 php mysql arrays codeigniter random

我正在尝试显示测验的随机问题,但我不想在测验中重复相同的问题。

我目前正在尝试:在我的模型中运行以获取随机问题

public function getRandom()
{
$idarray = $this->session->userdata('list');
//get a random question
$sql = "SELECT * FROM questions_table ORDER BY RAND() LIMIT 1";
$query = $this->db->query($sql);
$row = $query->row();

//make sure same question is not displayed twice ?
while(in_array($row->id, $idarray))
{
    $sql = "SELECT * FROM questions_table ORDER BY RAND() LIMIT 1";
    $query = $this->db->query($sql);
    $row = $query->row();
}

$idarray[] = $row->id;
$this->session->set_userdata('list',$idarray);




//get answers for that question and shuffle them
$query2 = $this->db->get_where('answers_table', array('qid' => $row->id));
$answers = $query2->result();
$shuff = (array)$answers;
shuffle($shuff);

return array('question' => $row, 'answers' => $shuff);

}

在我的 Controller 中,我有一个在测验开始时调用的函数

$idarray = array();
$this->session_set_userdata('list',$idarray);

但是当我尝试运行测验时它没有响应。

尝试过这个:

公共(public)函数 getRandom($ids) { //ids是从 Controller 传入的session数组

$random = rand(0, count($ids) -1);
echo count($ids);

unset($ids[$random]);
array_values($ids);
$this->session->set_userdata('idlist',$ids);
echo $random;

}

问题是有时数组不会减少并且显示相同的问题,即第一个计数是 4,然后是 3,然后是 2,然后是 2,而不是 1。

最佳答案

你可以尝试这样的事情(未经测试);

function selectAQuestionId($ids) {
    $id = rand(0, count($ids));

    // Now we need to remove the question id from the ids array
    unset($ids[$id]);

    // And re-index the array, you need to do this
    array_values($ids);

    // Store the questionId and remaining question Ids, in an array to return
    $response['questionId'] = $id;
    $response['ids'] = $ids;

    // Return the question and remaining ids
    return $response;
}

// Grab a list of question id's from your database
// i.e. "SELECT id FROM questions"
$questionIds = array(1,2,3,4,5,6);

// Grab a random question id and store the remaining questions ids
$response = selectAQuestionId(ids);

$questionId = $response['questionId'];
$ids = $response['ids']; // Ids now only contains the remaining question ids

// Use the $questionId, go get your question from the database

下次您想要获得另一个问题时,只需再次将返回的 ids 数组传递给 selectAQuestionId 函数即可。

关于php仅从mysql检索随机行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33707757/

相关文章:

javascript - 通过 Mailchimp 返回错误、Javascript 和 php 提交电子邮件

php - 使用 mySQL 和 php 创建正确的 JSON

php - CakePHP模型SQL查询条件参数

c++ - 堆栈或 BSS 或数据段上的数组最大大小

javascript - 如何编写一个函数将数组与不同类型的对象分开分组?

php - 如何使用 php 禁用树结构中的子级

Javascript运行php文件然后下载文件

php - Paypal:客户端身份验证失败

php - 如果数据库没有记录,则显示echo?

arrays - 将数组划分为子数组,使得子数组不包含重复元素