Tho*_*ens 50 php arrays associative-array
PHP数组可以为其元素提供数组.那些数组可以有数组等等.有没有办法找出PHP数组中存在的最大嵌套?一个示例是如果初始数组没有数组作为元素则返回1的函数,如果至少一个元素是数组则返回2,依此类推.
Jer*_*ten 74
这是另一个避免Kent Fredric指出的问题的替代方案.它为print_r()提供了检查无限递归(它做得很好)的任务,并使用输出中的缩进来查找数组的深度.
function array_depth($array) {
$max_indentation = 1;
$array_str = print_r($array, true);
$lines = explode("\n", $array_str);
foreach ($lines as $line) {
$indentation = (strlen($line) - strlen(ltrim($line))) / 4;
if ($indentation > $max_indentation) {
$max_indentation = $indentation;
}
}
return ceil(($max_indentation - 1) / 2) + 1;
}
Run Code Online (Sandbox Code Playgroud)
Jer*_*ten 61
这应该这样做:
<?php
function array_depth(array $array) {
$max_depth = 1;
foreach ($array as $value) {
if (is_array($value)) {
$depth = array_depth($value) + 1;
if ($depth > $max_depth) {
$max_depth = $depth;
}
}
}
return $max_depth;
}
?>
Run Code Online (Sandbox Code Playgroud)
编辑:非常快速地测试它似乎工作.
Ken*_*ric 43
请注意递归执行的示例.
PHP可以创建到阵列中的其他地方引用数组,可以包含有同样的递归引用的对象,任何纯粹的递归算法可以在这样的情况下,被认为是存在危险天真的一个,因为它会溢出栈深度递归,永不终止.
(好吧,它会在超过堆栈深度时终止,此时你的程序会致命终止,而不是我想你想要的)
在过去,我尝试过序列化 - >用字符串替换引用标记 - >根据我的需要进行反序列化(通常调试带有递归引用的回溯),这似乎工作正常,你到处都是漏洞,但它适用于那个任务.
对于你的任务,如果你发现你的数组/结构中有递归引用,你可能需要在这里查看用户提供的注释:http://php.net/manual/en/language.references.spot .PHP
然后以某种方式找到一种方法来计算递归路径的深度.
你可能需要拿出关于algorhthms的CS书籍并打出这些宝宝:
(很抱歉这么简短,但深入研究图形理论有点不适合这种格式;))
嗨这是另一种解决方案.
/*** IN mixed (any value),OUT (string)maxDepth ***/
/*** Retorna la profundidad maxima de un array ***/
function getArrayMaxDepth($input){
if( ! canVarLoop($input) ) { return "0"; }
$arrayiter = new RecursiveArrayIterator($input);
$iteriter = new RecursiveIteratorIterator($arrayiter);
foreach ($iteriter as $value) {
//getDepth() start is 0, I use 0 for not iterable values
$d = $iteriter->getDepth() + 1;
$result[] = "$d";
}
return max( $result );
}
/*** IN mixed (any value),OUT (bool)true/false, CHECK if can be used by foreach ***/
/*** Revisa si puede ser iterado con foreach ***/
function canVarLoop($input) {
return (is_array($input) || $input instanceof Traversable) ? true : false;
}
Run Code Online (Sandbox Code Playgroud)
在这里获得一些灵感并在PHP文档中找到这个RecursiveIteratorIterator之后,我找到了这个解决方案.
你应该使用这个,非常整洁:
function getArrayDepth($array) {
$depth = 0;
$iteIte = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iteIte as $ite) {
$d = $iteIte->getDepth();
$depth = $d > $depth ? $d : $depth;
}
return $depth;
}
Run Code Online (Sandbox Code Playgroud)
适用于PHP5和PHP7,希望这会有所帮助.
归档时间: |
|
查看次数: |
40710 次 |
最近记录: |