Suppose there is a random php array:
$array = [[1, 2],[2, 3, [3, 4]], [[2, [3, [a, b]], [2, 5]], [2, 6, 3]]]; How to find out the level of the maximum nested element? Those. nesting is now - level 4, these are elements of [a, b];
Suppose there is a random php array:
$array = [[1, 2],[2, 3, [3, 4]], [[2, [3, [a, b]], [2, 5]], [2, 6, 3]]]; How to find out the level of the maximum nested element? Those. nesting is now - level 4, these are elements of [a, b];
The main thing we need is is_array() .
$array = [[1, 2],[2, 3, [3, 4]], [[2, [3, [0, 0]], [2, 5]], [2, 6, 3]]]; function get_lvl(array $array) { $max_lvl = 1; foreach ($array as $value) { if (is_array($value)) { $lvl= get_lvl($value) + 1; if ($lvl> $max_lvl) { $max_lvl = $lvl; } } } return $max_lvl; } echo get_lvl($array); Thank you for helping @Other , but the essence of the problem solution remains the same :)
How to find out the level of the maximum nested element? Those. nesting now - level 4
You can use the getDepth() method of the RecursiveIteratorIterator class:
$array = [[1, 2],[2, 3, [3, 4]], [[2, [3, ['a', 'b']], [2, 5]], [2, 6, 3]]]; echo get_depth($array); Result: 4
function get_depth(Array $arr, $depth = 0): Int { $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr)); foreach ($it as $tmp) { $int = $it->getDepth(); $depth >= $int ?: $depth = $int; } return $depth; } Source: https://ru.stackoverflow.com/questions/812308/
All Articles