2

我有一个问题,我是否需要遍历“foreach-loop”中的数组。下面的 PHP 代码现在循环遍历 JSON 并寻找 ["Question"],并正确循环这些。

但是这些问题有不同数量的[“答案”]。而且这个 JSON 是动态生成的,所以我不知道之前会有多少问题/答案。

所以我需要的是 ["Answers"] 应该<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>";
} 
4

1 回答 1

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;
}
于 2013-08-16T22:58:01.770 回答