在php中随机整理数组不会真正地随机整理数组 [英] Shuffle an array in php does not really shuffle array
问题描述
我正在将数据库中的结果放入JSON数组中.我想对该数组进行随机化处理,因为现在它进入类别1、2、3、4,并且始终在同一行中获取数据.我如何将其随机化,以便从类别4、2、1、3(不一定按此顺序)获取数据.我的代码:
i am getting results from my database into a JSON array. I want to randomise this array because now it goes category 1, 2, 3, 4 and takes data always in same row. How can i randomise it so it takes data from category 4, 2, 1, 3(not necessarily in this order). My code:
$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);
我尝试过随机播放,但它只会返回true.我试过array_rand,但它返回键.我该怎么办?
I have tried shuffle but it only returns true. I have tried array_rand but it returns the key. How can i do this?
推荐答案
shuffle()
更改数组的位置,而不是返回具有不同元素顺序的新数组.因此,您所需要做的就是:
shuffle()
alters the array in place instead of returning a new array with different order of elements. So all you need to do is:
shuffle($first);
代替:
$first = shuffle($first);
这篇关于在php中随机整理数组不会真正地随机整理数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!