2015-11-04 108 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