有没有办法找出PHP数组的“深度”?

PHP数组可以为其元素包含数组。这些数组可以具有数组,依此类推。有没有办法找出PHP数组中存在的最大嵌套?一个示例是一个函数,如果初始数组不具有数组作为元素,则返回1;如果至少一个元素是数组,则返回2,依此类推。


千万里不及你
浏览 366回答 3
3回答

守着一只汪

应该这样做:<?phpfunction array_depth(array $array) {&nbsp; &nbsp; $max_depth = 1;&nbsp; &nbsp; foreach ($array as $value) {&nbsp; &nbsp; &nbsp; &nbsp; if (is_array($value)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $depth = array_depth($value) + 1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ($depth > $max_depth) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $max_depth = $depth;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return $max_depth;}?>编辑:非常快速地测试了它,它似乎可以工作。

慕丝7291255

这是避免Kent Fredric指出的问题的另一种选择。它为print_r()提供了检查无限递归的功能(它做得很好),并使用输出中的缩进来查找数组的深度。function array_depth($array) {&nbsp; &nbsp; $max_indentation = 1;&nbsp; &nbsp; $array_str = print_r($array, true);&nbsp; &nbsp; $lines = explode("\n", $array_str);&nbsp; &nbsp; foreach ($lines as $line) {&nbsp; &nbsp; &nbsp; &nbsp; $indentation = (strlen($line) - strlen(ltrim($line))) / 4;&nbsp; &nbsp; &nbsp; &nbsp; if ($indentation > $max_indentation) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $max_indentation = $indentation;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return ceil(($max_indentation - 1) / 2) + 1;}
打开App,查看更多内容
随时随地看视频慕课网APP