gpt4 book ai didi

php - 在 php 中随机排列数组并没有真正随机排列数组

转载 作者:行者123 更新时间:2023-12-05 09:20:46 26 4
gpt4 key购买 nike

<分区>

我正在将数据库中的结果放入 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 但它返回了 key 。我该怎么做?

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com