【发布时间】:2021-02-04 10:40:07
【问题描述】:
我尝试使用来自 url 的 PHP 解析 JSON。我需要一个没有子项的项目列表 - 意味着 children 字段应该是空数组,parent_id 不应该是 0 - 意味着不是父母。
JSON:
{
"body": {
"data": [
{
"id": 1,
"name": "car",
"parent_id": "0",
"children": [
{
"id": 2,
"name": "bmw",
"parent_id": "1",
"children": [
{
"id": 4,
"name": "bmw i8",
"parent_id": "2",
"children": []
}
]
},
{
"id": 3,
"name": "mustang",
"parent_id": "1",
"children": []
}
]
},
{
"id": 5,
"name": "clothes",
"parent_id": "0",
"children": []
},
{
"id": 6,
"name": "mobile",
"parent_id": "0",
"children": [
{
"id": 7,
"name": "apple",
"parent_id": "6",
"children": [
{
"id": 9,
"name": "Iphone 12 pro",
"parent_id": "7",
"children": []
},
{
"id": 10,
"name": "Iphone 11",
"parent_id": "7",
"children": []
}
]
},
{
"id": 8,
"name": "Xiaomi",
"parent_id": "6",
"children": []
}
]
}
]
}
}
预期输出:
[4,3,9,10,8]
这是我尝试过但不起作用的 php 代码。
$CategoryUrl = file_get_contents(self::CATEGORY_URL,true);
$array = json_decode($CategoryUrl,true);
$list = array();
foreach( $array['body']['data'] as $value ){
if (($value['parent_id'] != 0) && empty($value['children'])) {
foreach( $value['children'] as $val ){
$list[] = $val;
}
}
}
print_r($list);
【问题讨论】:
-
这能回答你的问题吗? How to use array_walk_recursive
-
有点相似,但对我没有帮助。 @nice_dev
-
它提供了通用机制——递归遍历整个数组正是您所需要的。你只需要修改回调。
标签: php arrays multidimensional-array