2016-03-29 48 views
0

我從我的數據庫中獲取結果到JSON數組中。我想隨機化這個數組,因爲它現在變成1,2,3,4類,並且總是將數據放在同一行。我如何隨機化它,因此它需要類別4,2,1,3(不一定按此順序)中的數據。我的代碼:在php中亂序數組並不真正洗牌數組

$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,但它返回密鑰。我怎樣才能做到這一點?

+0

功能'你shuffle_assoc'在你的代碼我看來完全正確的:如果你需要保存價值和它的鍵之間的關聯應該爲你做這項工作。 – Reversal

+0

這是更好的,如果你可以在這裏添加輸入數組,我們會弄清楚,你有什麼樣的索引在你的數組中.. – ameenulla0007

回答

2

shuffle()改變數組,而不是以不同的元素順序返回一個新的數組。因此,所有你需要做的是:

shuffle($first); 

相反的:

$first = shuffle($first); 
+0

我多麼愚蠢......謝謝 – BRG