我有一个如下所示的“树”数组。这是一个导航。现在我想删除所有级别> = 3.所以我只想获得前两个级别的数组。有没有办法像这样修剪/缩短数组。
你有什么我可以寻找的提示吗?
Array
(
[0] => Array
(
[name] => Home
[level] => 1
[sub] =>
)
[1] => Array
(
[name] => Products
[level] => 1
[sub] => Array
(
[56] => Array
(
[name] => Product 1
[level] => 2
[sub] => Array
(
[61] => Array
(
[name] => Product 1b
[target] =>
[level] => 3
[sub] =>
)
)
)
[57] => Array
(
[name] => Product 2
[level] => 2
[sub] =>
)
)
)
[2] => Array
(
[name] => Contact
[level] => 1
[sub] =>
)
[3] => Array
(
[name] => Something Else
[level] => 1
[sub] =>
)
)
答案 0 :(得分:0)
$data = [
0 => ['name' => 'Home', 'level' => 1, 'sub' => []],
1 => [
'name' => 'Products',
'level' => 2,
'sub' => [
'56' => [
'name' => 'Product 1',
'level' => 2,
'sub' => [
'61' => [ 'name' => 'Product 1b', 'target' => '', 'level' => 3, 'sub' => ''],
],
],
'57' => ['name' => 'Product 2', 'level' => 2, 'sub' => '']
]
],
2 => ['name' => 'Contact', 'level' => 1, 'sub' => []],
3 => ['name' => 'Something Else', 'level' => 1, 'sub' => []]
];
function processArray(&$arr) {
foreach ($arr as $key => $array) {
if ($array['level'] >= 3) {
unset($arr[$key]);
}
if (!empty($arr[$key]['sub'])) {
processArray($arr[$key]['sub']);
}
}
}
processArray($data);