我正在用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]];
答案 0 :(得分:1)
如前所述,您的代码运行正常: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>";
}