0

Hi,

I have an array like this:

Array
(
    [23] => 0
    [12] => Array
        (
            [2] => Array
                (
                    [66] => 0
                    [67] => 0
                    [68] => Array
                        (
                            [14] => 0
                            [15] => 0
                        )

                )

            [3] => 0
            [4] => Array
                (
                    [56] => 0
                    [77] => 0
                    [78] => 0
                )

        )

    [45] => 0
)

(the tree can continue endlessly). I need a function to determine the level of a key. By level I mean how deep the key goes in the array nest. For example, if I pass the key 23 to the function, it would return 0 as the first level, key 3 would return 1 as the second level, key 56 would return 2, key 14 would return 3 etc. Any suggestions? Thanks.

Update:
I've come up with this function:

private function getLevel($array,$id) {
        $level = 0;

        foreach($array as $key => $value) {
            if (array_key_exists($id,$array)) {
                return $level;
            } else {
                if (is_array($value)) {
                    $this_level = $this->getLevel($value,$id) + 1;

                    if ($this_level > $level) {
                        $level = $this_level;
                    }
                }
            }
        }

        return $level;

    }

However, if I enter 66 as $id, it returns 2 (which is correct), if I enter 15, it returns 3 (which is also correct), but if I enter 56, it returns 3, where it should be 2. Any suggestions here?

Edited by Buppy

2
Contributors
1
Reply
2
Views
4 Years
Discussion Span
Last Post by pritaeas
0

Build a recursive function. Pass the array as parameter and initial level 0. First determine if the key exists there. If it does return the level. If it does not, search a new array in the available values, and recall the function with an incremented level.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.