当我执行我的代码以获得在php测验中显示我的问题和答案的字符串时,我遇到了一些错误。 COM / ZCy6G.jpg
答案 0 :(得分:0)
您所看到的错误涉及数组到字符串的转换,这是由此行引起的:
echo $key . " : " . $value . "<br>";
如果你在该循环中使用var_dump($ value),你会发现$ value有时是数组,而不是字符串。您可以迭代$ value数组中的值,如下所示:
foreach($quizHistoryQ[$keys[$i]] as $key => $value) {
echo $key . " : ";
//note: in OP's specific example, only is_array test is needed. is_object test can be omitted in this case since we know $value will never be an object
if (is_array($value) || is_object($value)) {
foreach($value as $item) {
echo $item . '<br />';
}
} else {
echo $value . '<br />';
}
}
这将测试$ value是否为数组或字符串。如果它是一个数组,它会遍历它。否则,它只是回显字符串。
答案 1 :(得分:0)
我当前的php版本不支持数组文字构造函数的javascript样式,因此我必须使用原始样式。下面的代码具有最小的样式,但似乎正确输出问题和选项。
<html>
<head>
<title>quiz</title>
<style>
form{ display:block; float:none; width:90%;margin:1rem auto;box-sizing:content-box;padding:1rem;border:1px solid black; }
ul{}
li{}
h3{margin:2remauto 1rem auto;}
</style>
</head>
<body>
<?php
$quizHistoryQ = array(
"Q1" => array(
"question"=>"This is the First question",
"options" => array(
"this is option 1",
"this is option 2",
"this is option 3"
),
"answer" =>2
),
"q2" => array(
"question"=>"This is the Question String for question 2",
"options" => array(
"this is option A",
"this is option B",
"this is option C"),
"answer" =>1
),
"q3" =>array(
"question"=>"This is the Question String for question 3",
"options" => array(
"this is option X",
"this is option Y",
"this is option Z"
),
"answer" =>0
)
);
echo "
<form name='quiz' method='post'>";
foreach( $quizHistoryQ as $index => $arr ){
$question=$arr['question'];
$options=$arr['options'];
$answer=$arr['answer'];
echo '<h3>Question: '.$index.': '.$question.'</h3>';
echo '<ul>';
foreach( $options as $i => $option ) echo "<li><input type='radio' name='{$index}[]' value='{$i}'/>{$option}";
echo '</ul>';
}
echo "
<input type='submit' name='sub' value='Submit'/>
</form>";
?>
</body>
</html>