For example, there is a multi-dimensional array: array (1, 3, 4), array (1, 2, 3). For example, there is a multi-dimensional array:
array( array( array(1,3,4), array( array( 1,2,3 ) ) ), array( array(1,2), array(1) ) )
The depth of this array is 5, so how to quickly determine the depth of an array.
Solution 1:
Using Iterator in SPL, there is a getDepth method in the RecursiveIteratorIterator class to get the depth
Solution 2:
Solution 3:
$arr = array(array( array(array(“5″, “6″), “7″, “8″)),2,array(array(array(“5″, “6″), “7″, “8″,array( “7″,“8″))),4); echo getArrDemp($arr); function getArrDemp($array){ static $offset = 0; $arr_str = serialize($array); $num = substr_count($arr_str,'{'); $result = array(); for($i=0;$i<$num;$i++){ $l_pos = strpos($arr_str, '{', $offset); $temp_str = substr($arr_str,0,$l_pos); $offset = $l_pos + 1; $result[] = substr_count($temp_str,'{')-substr_count($temp_str,'}'); } array_multisort($result,SORT_DESC); return ++$result[0]; }
Solution 4: Recursive implementation
Solution 5: simple deep computing functions:
$max_depth) { $max_depth = $depth; } } } return $max_depth; } $array = array( array("11"), array(),array( array(array("5", "6"), "7", "8")),array( array(array("5", "6"), "7", "8")), "9", "10"); echo array_depth($array); ?>