PHP tree array remove levels

I have an "tree" array like the following. This is a navigation. Now i want to remove all levels >= 3. So i only want to get an array with the first two levels. Is there a way to trim/shorten the array like that.

Do you have a hint for me what i can look for?

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] => 
        )

)

Answers


$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);

Need Your Help

golang, revel, How to parse post json?

php json curl go revel

I'm rather new in golang, but I'm trying hard..

Searching for a particular value then pasting into another workbook

excel vba excel-vba

Let me give you a basic understanding of my what I'm trying to do. I have two workbooks: Master Workbook and Workbook A. Information in Workbook A will be inputted into the Master Workbook. In Work...