2013-04-13 87 views
0

我需要一些幫助從PHP中的多維數組獲取數據。這個數組充滿了問題,並回答了這些問題。每個問題可以有多個答案,但對於大多數問題答案的數量是不同的。這是它的後續代碼var_dump:php多維數組獲取數據

object(CommandResponse)#3 (3) 
{ 
    ["success"]=> bool(true) 
    ["message"]=> string(6) "Got it" 
    ["value"]=> array(2) 
    { 
     [0]=> array(3) 
     { 
      ["questionId"]=> string(2) "25" 
      ["question"]=> string(9) "Question 1" 
      ["answers"]=> array(2) 
      { 
       [0]=> array(2) 
       { 
        ["answerId"]=> string(1) "1" 
        ["answer"]=> string(9) "Answer 1" 
       } 
       [1]=> array(2) 
       { 
        ["answerId"]=> string(2) "18" 
        ["answer"]=> string(22) "Answer 2 for question 1" 
       } 
     } 
    } 
    [1]=> array(3) 
    { 
     ["questionId"]=> string(2) "26" 
     ["question"]=> string(9) "Question 2" 
     ["answers"]=> array(1) 
     { 
      [0]=> array(2) 
      { 
       ["answerId"]=> string(2) "17" 
       ["answer"]=> string(9) "Answer 2" 
      } 
     } 
    } 
} 

我想從它那裏得到這樣的:

Question 1 
    Answer 1 
    Answer 2 
Question 2 
    Answer 1 
    Answer 2 

到目前爲止,我已經試過:

獲取的問題是這樣的:print $myArray->value[0]['question']; 獲取這樣的第一個答案:print $myArray->value[0]['anwsers'][0]['answer'];

我也試着循環它在一些foreach循環,但我沒有得到任何好的fr噢它。

foreach ($myArray->value as $key => $value) 
{ 
    print $value['question'].' - '; 
    print $value['answers'][0]['answer'].'<br />'; 
} 
+3

,你試過嗎?你的代碼在哪裏? – mkjasinski

+0

謝謝你提醒我,我編輯了這個問題。 – ivica

+2

爲什麼不在循環中使用循環?第一個(上)循環用於提問,第二個內循環用於回答這個問題..? – David

回答

1

我們假設數據在變量$object中提供。

// Assign questions array to $questions 
$questions = $object->value; 

// Loop through questions 
echo '<ul>'; 
foreach ($questions as $q) { 
    echo '<li>' . $q['question']; 

    // Loop through answers 
    echo '<ul>'; 
    foreach($q['answers'] as $a) { 
     echo '<li>' . $a['answer'] . '</li>'; 
    } 
    echo '</ul>'; 
    echo '</li>'; 
} 
echo '</ul>'; 

應輸出所需

  • 問題1
    • 回答1
    • 回答2
  • 問題2
    • 回答1
    • 答案2
+0

謝謝你的答案,但我得到這個'注意:試圖獲得非對象的屬性'因爲'$ q'不是一個對象,而是一個數組 – ivica

+0

是的,對不起。我把它混在一起。我在答案中糾正了它。 –

+0

完美。不要道歉,你已經幫了我很多忙:) – ivica