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?