我使用以下代码作为解析我的 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 文件时如何将子对象放在正确的位置的任何想法?
它的工作原理如下:
$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'};
}