我尝试显示随机问题以进行测验,但我不想在测验中重复相同的问题。
我目前正在尝试:在我的模型中运行以获得随机问题
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);
}
在我的控制器中,我有一个在测验开始时调用的函数
$idarray = array();
$this->session_set_userdata('list',$idarray);
但是当我尝试进行测验时,它没有回应。
试过这个:
公共函数getRandom($ ids) { // ids是从控制器传入的会话数组
$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。
答案 0 :(得分:0)
您可以尝试这样的事情(未经测试);
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函数。