Shuffle an array in php does not really shuffle ar

2019-09-17 17:01发布

问题:

This question already has an answer here:

  • How does MySQL's ORDER BY RAND() work? 4 answers

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);

I have tried shuffle but it only returns true. I have tried array_rand but it returns the key. How can i do this?

回答1:

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);

Instead of:

$first = shuffle($first);