我有一个数组,
$arr = Array(
Array(
'title' => 'Title 1',
'id' => 1,
'parent' => 0,
'children' => [
Array(
'title' => 'Title 1.1',
'id' => 4,
'parent' => 1,
'children' => [
Array(
'title' => 'Title 1.1.1',
'id' => 19,
'parent' => 4
),
Array(
'title' => 'Title 1.1.2',
'id' => 123,
'parent' => 4
)
]
),
Array(
'title' => 'Title 1.2',
'id' => 4,
'parent' => 1,
'children' => [
Array(
'title' => 'Title 1.2.1',
'id' => 19,
'parent' => 4
)
]
)
]
),
Array(
'title' => 'Title 2',
'id' => 1,
'parent' => 0
)
);
我希望" flatten"通过"切割"将子节点分成单独的项目,给我一个包含这些项目的数组:
$arr = Array(
Array(
'title' => 'Title 1',
'id' => 1,
'parent' => 0
),
Array(
'title' => 'Title 1.1',
'id' => 4,
'parent' => 1
),
Array(
'title' => 'Title 1.1.1',
'id' => 19,
'parent' => 4
),
Array(
'title' => 'Title 1.1.2',
'id' => 123,
'parent' => 4
),
Array(
'title' => 'Title 1.2',
'id' => 4,
'parent' => 1
),
Array(
'title' => 'Title 1.2.1',
'id' => 19,
'parent' => 4
),
Array(
'title' => 'Title 2',
'id' => 1,
'parent' => 0
)
);
有人可以帮我吗?非常感谢!
答案 0 :(得分:1)
这会对你有帮助..
<?php
function recursiveFind(array $items,&$return=array())
{
foreach($items as $item){
if(array_key_exists('children',$item)){
$childs = $item['children'];
unset($item['children']);
array_push($return,$item);
recursiveFind($childs,$return);
}else{
array_push($return,$item);
}
}
return $return;
}
$arr = Array(
Array(
'title' => 'Title 1',
'id' => 1,
'parent' => 0,
'children' => [
Array(
'title' => 'Title 1.1',
'id' => 4,
'parent' => 1,
'children' => [
Array(
'title' => 'Title 1.1.1',
'id' => 19,
'parent' => 4
),
Array(
'title' => 'Title 1.1.2',
'id' => 123,
'parent' => 4
)
]
),
Array(
'title' => 'Title 1.2',
'id' => 4,
'parent' => 1,
'children' => [
Array(
'title' => 'Title 1.2.1',
'id' => 19,
'parent' => 4
)
]
)
]
),
Array(
'title' => 'Title 2',
'id' => 1,
'parent' => 0
)
);
echo '<pre>';
print_r(recursiveFind($arr));