早上好,给定以下数据结构(为便于阅读,采用 JSON 格式)
[
{
"parent": "root",
"active": "1",
"label": "Index",
"route": "/",
"children": [
{
"parent": "/",
"active": "1",
"label": "Products",
"route": "/products",
"children": [
{
"parent": "/products",
"active": "0",
"label": "Test",
"route": "/test"
}
]
}
]
},
{
"parent": "root",
"active": "1",
"label": "404",
"route": "/404"
},
{
"parent": "root",
"active": "1",
"label": "Login",
"route": "/login"
}
]
我在从以下结构的函数返回时遇到了很大的麻烦:
[
{
"parent": "root",
"active": "1",
"label": "Index",
"route": "/"
},
{
"parent": "/products",
"active": "0",
"label": "Test",
"route": "/test"
},
{
"parent": "/",
"active": "1",
"label": "Products",
"route": "/products"
},
{
"parent": "root",
"active": "1",
"label": "404",
"route": "/404"
},
{
"parent": "root",
"active": "1",
"label": "Login",
"route": "/login"
}
]
本质上,我想遍历所有子项并用嵌套数组中的每个父项和子项填充一个新数组,我尝试了 array_merge
、RecursiveIteratorIterator
、iterator_to_array
、array_map
,但它总是在递归时出现问题。当 children 只有一层深度但两层或更多层完全崩溃时,我设法做到了。
最佳答案
简单的
function flatten($items, &$r) {
foreach($items as $item) {
$c = isset($item->children) ? $item->children : null;
unset($item->children);
$r []= $item;
if($c)
flatten($c, $r);
}
}
flatten(json_decode($json), $r);
print_r($r);
这会将结果累积在一个缓冲区中,通过引用传递。这比在每次迭代中构建一个全新的数组要有效得多,后者基本上是 Shlemiel the painter's algorithm 的变体。 .
如果您更喜欢函数式方法,可以使用 generators :
function flatten($items) {
foreach($items as $item) {
$c = isset($item->children) ? $item->children : [];
unset($item->children);
yield $item;
foreach(flatten($c) as $child)
yield $child;
}
}
foreach(flatten(json_decode($json)) as $item)
print_r($item);
关于php - 展平具有父子关系的数组,以便所有子项都在父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28393612/