在 PHP 中打乱多维数组

Shuffle Multidimensional Array in PHP

我正在 PHP 开发一个测验应用程序,在 30 个问题中,我想向用户随机显示 10 个问题。使用多维数组,我用那里的选项保存问题。无法访问数组的随机结果。

$shop = array( array( question => "Q.1. What term describes hardware and software designed to help people with disabilities?", 
                      option1 => "Computer aided development",
                      option2 => "Assistive technology",
                      option3 => "Electronic learning products",
                      option4 => "Specialized support",
                    ),
               array( question => "Q.2. What is the process of simultaneously recording and compressing audio called?", 
                      option1 => "Ripcording",
                      option2 => "Audio filtering",
                      option3 => "Signal processing",
                      option4 => "Encapsulating",
                    ),
               array( question => "Q.4. Select the correct order:", 
                      option1 => "3D video games",
                      option2 => "Virtual reality",
                      option3 => "Hologram",
                      option4 => "4D Max",
                    ),
);

$rand_keys = array_rand($shop,2);

$shop[$rand_keys[0]];

如前所述,您的代码工作正常 :P

如果你想保存结果,你所要做的就是 $randomQuestion = $shop[$rand_keys[0]];

要访问问题字段,只需执行 $randomQuestion['question']$shop[$rand_keys[0]]['question'];

如果您想随机抽取 10 个问题:

$rand_keys = array_rand($shop, 10);

$questions = array();  // This array will hold the 10 random questions
foreach($rand_keys as $rand_key){
    array_push($questions, $shop[$rand_key]); // This will add the current random question into $questions
}

$questions 是包含您的 10 个问题的数组。

如果要打印所有问题,

foreach ($questions as $question){
    echo $question['question']. "<br>";
    echo $question['option1']. "<br>";
    echo $question['option2']. "<br>";
    echo $question['option3']. "<br>";
    echo $question['option4']. "<br>";
}