PHP中的洗牌多维数组
我正在用PHP开发一个测验应用程序,在30个问题中,我想向用户展示10个随机问题。使用多维数组,我保存了带有三个选项的问题。无法从数组访问随机结果PHP中的洗牌多维数组,php,arrays,php-5.3,Php,Arrays,Php 5.3,我正在用PHP开发一个测验应用程序,在30个问题中,我想向用户展示10个随机问题。使用多维数组,我保存了带有三个选项的问题。无法从数组访问随机结果 $shop = array( array( question => "Q.1. What term describes hardware and software designed to help people with disabilities?", option1 => "Computer
$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\u keys=array\u rand($shop,10)
$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>";
}
foreach($questions as$question){
回音$question['question']。“
”;
回显$question['option1']。“
”;
回声$question['option2']。“
”;
回音$question['option3']。“
”;
回音$question['option4']。“
”;
}
Tryprint\r($shop[$rand\u keys[0]])代码>检查代码是否正常工作?您有哪些问题$shop[$rand_keys[0]]代码>是一个数组。您应该能够通过执行$shop[$rand\u keys[0]]['question']
访问该问题。代码也没有对数组执行任何操作。我猜你想回显它或将结果存储在变量中?@JonTan,我只想保存结果?如何分别保存每个选项?像option1、option2等$option1=$shop[$rand_keys[0]]['option1']
会做这个诀窍如果我必须保存10个问题我需要做$shop[$rand_keys[0]['question']直到$shop[$rand_keys[9]['question']]@Roger:你可以用foreach
超过$rand_keys
。编辑答案,展示你将如何做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>";
}