2015-11-04 43 views
-1

我有一個js對象,看起來像這樣:解析多維JS對象在PHP

0: Object answer: Object answer1: "fweq" answer2: "qwef" answer3: "fqwef" answer4: "vrevwe" question: Object content: "<p>my content</p>" title: "test" type: Object type: "addmcq"

我想迭代並在PHP解析此。然而,它攪亂了我的頭。

我的PHP是這樣的:

$question = $_POST['data']; 
$question = json_decode($question, true); 
var_dump($question); 
foreach($question as $q) { 
    foreach($q as $item) { 
     $type = $item['type']; //Echoes the type correctly 
      echo $item['content']; //Does nothing 
      echo $item['answer1']; // Does nothing 
      echo $item['answer2']; // -- 
      echo $item['answer3']; // -- 
      echo $item['answer4']; // -- 

    } 
} 

$類型將回聲出無論是在類型的對象,但$項目[ 'ANSWER1']不會。

我該如何迭代答案數組?

繼承人的var_dump輸出(問題):

array(1) { 
    [0]=> 
    array(3) { 
    ["question"]=> 
    array(2) { 
     ["title"]=> 
     string(48) " 
        test 
        " 
     ["content"]=> 
     string(12) "<p>asetw</p>" 
    } 
    ["answer"]=> 
    array(4) { 
     ["answer1"]=> 
     string(4) "fweq" 
     ["answer2"]=> 
     string(4) "qwef" 
     ["answer3"]=> 
     string(5) "fqwef" 
     ["answer4"]=> 
     string(6) "vrevwe" 
    } 
    ["type"]=> 
    array(1) { 
     ["type"]=> 
     string(6) "addmcq" 
    } 
    } 
} 
+0

再次看你的數組結構。 'var_dump($ q,$ item);' –

+0

謝謝u_mulder。 – Havihavi

回答

3

這些行應該是

echo $item['question']['content'];// suggested by @zedd 
echo $item['answer']['answer1']; 
echo $item['answer']['answer2']; 
echo $item['answer']['answer3']; 
echo $item['answer']['answer4']; 

這是因爲所有answer1,answer2,...都存在裏面answer指數

+0

這是正確的,也是$ item ['question'] ['content']第一行 – BobbyTables

+0

謝謝你。我沒有看到實際上。 –

+0

非常感謝! :)之後,這對我來說更有意義。 我最終刪除了第二個foreach循環和你的答案。奇蹟般有效! – Havihavi