2013-08-16 80 views
2

我有一個問題,我是否需要在「foreach-loop」中循環訪問數組。下面的PHP代碼現在循環遍歷JSON並查找[「問題」],並正確地循環這些代碼。如何通過在foreach循環內的JSON數組「循環」?

但這些問題有不同數量的[「答案」]。此外,這個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

如果你明白如何使用數組的foreach循環,你可以json_decode你的數組並通過它循環。 – Mic1780

+0

你有一個分析錯誤:語法錯誤,意想不到的'{'第5行 – raam86

+1

感謝@ raam86!意外複製一個額外的,但我現在刪除它 – Kim

回答

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; 
} 
+0

感謝您的一個很好的解釋,只是做了一個小的調整,它完美的作品!再次感謝! – Kim