我将数据库中的结果转换为JSON数组。我想随机化这个数组,因为它现在属于1,2,3,4类并且数据总是在同一行。我如何随机化它,以便从第4,2,1,3类(不一定按此顺序)中获取数据。我的代码:
$query = $handler->query('SELECT DISTINCT c.cat_description, c.cat_name, c.cat_id, q.question, q.q_id FROM `categories` c
INNER JOIN `questions` q ON c.cat_id = q.cat_id ');
$records = array();
$records = $query->fetchAll(PDO::FETCH_ASSOC);
$first = array();
$second = array();
$third = array();
$query->closeCursor();
foreach($records as $k => $v){
$first[] = array("category_name" => $v['cat_name'], "category_id" => $v['cat_id'], "category_description" => $v['cat_description'], "question_name" => $v['question'], "question_id" => $v['q_id'], "question_answers" => array());
$second[] = $v['question'];
}
foreach ($second as $key => $value) {
$ques = $value;
$qu = $handler->query("SELECT a.quest_id, a.answer, a.iscorrect, a.anser_id FROM `answers` a INNER JOIN `questions` q ON a.quest_id = q.q_id WHERE q.question = '$ques' ");
$third = $qu->fetchAll(PDO::FETCH_ASSOC);
foreach($third as $tk => $tv){
$third[$tk]['answer'.($tk+1)] = $tv['answer'];
$third[$tk]['iscorrect'.($tk+1)] = $tv['iscorrect'];
}
foreach ($first as $k => $v) {
$first[$key]['question_answers'] = $third;
}
}
function shuffle_assoc($list) {
if (!is_array($list)) return $list;
$keys = array_keys($list);
shuffle($keys);
$random = array();
foreach ($keys as $key) {
$random[$key] = $list[$key];
}
return $random;
}
$first = shuffle($first);
$j['quiz'] = $first;
echo json_encode($j);
我试过shuffle但它只返回true。我尝试过array_rand但它返回了密钥。我怎么能这样做?
答案 0 :(得分:4)
shuffle()
改变数组,而不是返回具有不同元素顺序的新数组。所以你需要做的就是:
shuffle($first);
而不是:
$first = shuffle($first);