Php 如何从数据库中随机化问题和相应答案
我一直在做一个测验应用程序,我被困在一个点上。我正在使用PHP和MySQL来实现它因此,我现在想随机检索数据库中的问题。但是,当我试着用rand()来回答问题时,它的选择与应该的不同我应该怎么做将问题的随机性与答案同步Php 如何从数据库中随机化问题和相应答案,php,mysql,Php,Mysql,我一直在做一个测验应用程序,我被困在一个点上。我正在使用PHP和MySQL来实现它因此,我现在想随机检索数据库中的问题。但是,当我试着用rand()来回答问题时,它的选择与应该的不同我应该怎么做将问题的随机性与答案同步 class Quiz { protected $_db; protected $_answers = array(); protected $_questions = array(); protected $_question; protected $_users; prote
class Quiz {
protected $_db;
protected $_answers = array();
protected $_questions = array();
protected $_question;
protected $_users;
protected $_leaderboard;
protected $_currentuser;
public $session;
public function __construct(\Pimple $container)
{
$this->_currentuser = $container['user'];
$this->session = $container['session'];
$this->_leaderboard = $container['leaderboard'];
$this->_users = $this->_leaderboard->getMembers();
try
{
//$this->_db = new PDO('mysql:host='.Config::$dbhost.';dbname='.Config::$dbname, Config::$dbuser, Config::$dbpassword);
$this->_db = $container['db'];
$this->_populateQuestions();
}
catch (\PDOException $e)
{
return $e;
}
}
public function getAnswers($questionid = false)
{
if ($questionid)
{
//pull answers from db for only this question
$answersql = "SELECT text FROM answers where question_id = :id ORDER BY correct DESC";
$stmt = $this->_db->prepare($answersql);
$stmt->bindParam(':id', $questionid, \PDO::PARAM_INT);
$stmt->execute();
while ($result = $stmt->fetchObject())
{
array_push($this->_answers,$result->text);
}
}
else
{
//pull all answers from db grouped by question
$answersql = "SELECT group_concat( a.text ORDER BY a.correct DESC SEPARATOR '~' ) FROM answers a GROUP BY a.question_id";
$stmt = $this->_db->query($answersql);
$stmt->execute();
$resultset = $stmt->fetchAll(\PDO::FETCH_NUM);
foreach ($resultset as $csv)
{
$tmparray = explode('~', $csv[0]);
array_push($this->_answers,$tmparray);
}
}
return $this->_answers;
}
public function getQuestion($questionid)
{
$questionsql = "select text from questions where id = :id order by rand()";
$stmt = $this->_db->prepare($questionsql);
$stmt->bindParam(':id', $questionid, \PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetchObject();
$this->_question = $row->text;
return $this->_question;
}
public function getQuestions()
{
return $this->_questions;
}
private function _populateQuestions()
{
$questionsql = "select text from questions order by id asc";
$stmt = $this->_db->query($questionsql);
$stmt->execute();
while ($row = $stmt->fetchObject())
{
$this->_questions[] .= $row->text;
}
}
随机化与问答数组长度相同的数组,将值作为数组索引,然后迭代测验问答并更改其键。每个人的顺序都是一样的。以下是一个例子:
$order = [1, 0];
$ques = ['foo', 'bar'];
$ans = ['baz', 'bop'];
$new_ques = [];
$new_ans = [];
foreach($order as $k=>$v){
$new_ques[$v] = $ques[$k];
$new_ans[$v] = $ans[$k];
}
ksort($new_ques);ksort($new_ans);
var_dump($new_ques, $new_ans);
这有点低效,因为它创建了一个新数组来放置值,然后对它们进行排序,但它应该可以满足您的需要。
从id=:id order by rand()的问题中选择文本。
应该只检索具有您传递的id
的问题。你确定这些问题不对吗?你是什么意思?你能详细说明一下吗?