2015-06-12 16 views
2

與嵌套對象解析JSON我使用下面的代碼爲我解析JSON基地時:http://soyuka.me/streaming-big-json-files-the-good-way/發行使用流解析器

它工作正常的大部分JSON數據我有,但一旦它遇到JSON對象作爲直接子對象而失敗。

這是我的JSON的簡化版本:

[ 
    { 
     "title": "Title", 
     "child_object": { 
      "title": "Child Title" 
     } 
    }, 
    { 
     "title": "Title 2", 
     "child_object": { 
      "title": "Child Title 2" 
     } 
    } 

] 

之後被解析我結束了這樣的結果:

Array 
(
    [0] => Array 
     (
      [0] => Array 
       (
        [title] => Title 
       ) 

      [child_object] => Array 
       (
        [title] => Child Title 2 
       ) 

      [2] => Array 
       (
        [title] => Title 2 
       ) 

     ) 

) 

如果我把孩子對象到一個數組的解析器將產生這個結果與如果我在JSON數據上使用json_decode相同:

Array 
(
    [0] => Array 
     (
      [0] => Array 
       (
        [title] => Title 
        [child_object] => Array 
         (
          [0] => Array 
           (
            [child_title] => Child Title 
           ) 

         ) 

       ) 

      [1] => Array 
       (
        [title] => Title 2 
        [child_object] => Array 
         (
          [0] => Array 
           (
            [title] => Child Title 2 
           ) 

         ) 

       ) 

     ) 

) 

在解析JSON文件時如何獲取子對象的適當位置的任何想法?

回答

0

它的工作原理如下圖所示:

$str = '[ 
    { 
     "title": "Title", 
     "child_object": { 
      "title": "Child Title" 
     } 
    }, 
    { 
     "title": "Title 2", 
     "child_object": { 
      "title": "Child Title 2" 
     } 
    } 

]'; 

$json = json_decode($str); 

foreach($json as $data) { 
    echo $data->{'title'}; 
    echo $data->{'child_object'}->{'title'}; 
} 
+0

真正的JSON文件我用的是太大json_deocde,因爲它運行的內存,否則我會使用它。 –