我有一个问题,我是否需要在“foreach-loop”内循环一个数组。下面的PHP代码现在循环遍历JSON并查找[“Question”],并正确循环这些代码。
但这些问题有不同数量的[“答案”]。这个JSON也是动态制作的,所以我不知道之前会有多少个问题/答案。
所以我需要的是[“答案”]应该在每个问题内循环<li>
。
这里的一些专业知识真的很棒!
JSON
["Questions"]=>
array(2) {
[0]=>
object(stdClass)#13 (2) {
["Question"]=>
string(30) "My first questions is this...."
["Answers"]=>
array(2) {
[0]=>
object(stdClass)#14 (2) {
["Answers"]=>
string(18) "I like this answer"
["Correct"]=>
bool(true)
}
}
}
[1]=>
object(stdClass)#16 (2) {
["Question"]=>
string(22) "Another funny question"
["Answers"]=>
array(2) {
[0]=>
object(stdClass)#17 (2) {
["Answers"]=>
string(9) "Or is it?"
["Correct"]=>
bool(false)
}
[1]=>
object(stdClass)#18 (2) {
["Answers"]=>
string(10) "Yes it is!"
["Correct"]=>
bool(true)
}
}
}
}
PHP
$questions = array();
$i = 0;
foreach($question as $key => $items) {
$i++;
if ($i>1) {$hide=' hide';}
$questions[] = "
<div class='question-holder" . $hide . "' id='q" . $i . "'>
<h2>" . $items->Question . "</h2>
<ul class='answers' id='quiz-answers" . $i . "'>
<li>
<input tabindex='1' type='radio' name='txtAnswer" . $i . "' id='txtAlt1' value='sdsds'>
<label for='txtAlt1'><span>" . $items->Answers[0]->Answers . "</span></label>
</li>
</ul>
</div>";
}
答案 0 :(得分:2)
使用嵌套循环来获得答案。
$tab = 0;
foreach ($question as $items) {
$i++;
$j = 0;
if ($i > 1) { $hide = ' hide'; }
$this_q = "<div class='question-holder" . $hide . "' id='q" . $i . "'>
<h2>" . $items->Question . "</h2>
<ul class='answers' id='quiz-answers" . $i . "'>
";
foreach ($items->Answers as $ans) {
$tab++;
$j++;
$qa = "$i-$j";
$this_q .= "<li>
<input tabindex='" . $tab . "' type='radio' name='txtAnswer" . $qa . "' id='txtAlt" . $qa . "' value='sdsds'>
<label for='txtAlt" . $qa . "'><span>" . $ans->Answers . "</span></label>
</li>
";
}
$this_q .= "</ul>
</div>";
$questions[] = $this_q;
}