2012-08-22 24 views
1

的递归嵌套的数组的数组查找最大值如果数组初始化为:从含有正整数和/或正整数

$arr = array(array(141,151,161),2,3,array(101,102,array(303,404,606,555,789,array(1000,22,9999,array(9057,100000),522)))); 

然后,结果应该是:100000

我已经写了函数来解决这个问题,但我需要更少的字节和更少的代码内存。

我的功能是:

function MaxArray($arr){ 
$length = count($arr); 
global $maxValue; 
for($i=0;$i<$length;$i++){ 
     if(is_int($arr[$i])){ 

       if($maxValue < $arr[$i]){ 
        $maxValue = $arr[$i]; 
       } 

     } 
     elseif(is_array($arr[$i])){  
       MaxArray($arr[$i]); 
      } 
     } 
    return $maxValue; 
} 

回答

5

Taken from PHP manual但创作由我:

/** 
* @param array $array 
* 
* @return int|null Returns the largest value of the array. Returns NULL if no 
*  integers are found. 
*/ 
function array_max_recursive(array $array) { 
    $max = NULL; 
    $stack = array($array); 

    do { 
     $current = array_pop($stack); 
     foreach ($current as $value) { 
      if (is_array($value)) { 
       $stack[] = $value; 
      } elseif (filter_var($value, FILTER_VALIDATE_INT) !== FALSE) { 
       // max(NULL, 0) returns NULL, so cast it 
       $max = (int) max($max, $value); 
      } 
     } 

    } while (!empty($stack)); 

    return $max; 
} 

  • 这个功能实际上不是递归的,但是满足它的工作原理上要求子阵列。我喜欢在没有运行时间堆栈的情况下不时进行操作。
  • 它返回int类型的东西,从不是int的字符串表示形式。例外是当你提供一个不包含任何整数的数组时。它将返回NULL。
  • 它忽略非数组,非int值。
4

行走嵌套数组的方便函数是array_walk_recursive()。这意味着您不必担心自己处理递归问题,并可以随时处理任务,在这种情况下可以找到最大值。

function MaxArray($arr) { 
    $max = FALSE; 
    array_walk_recursive($arr, function ($current) use (&$max) { 
     if ($max === FALSE) { 
      $max = $current; 
     } else { 
      $max = max($current, $max); 
     } 
    }); 
    return $max; 
} 
+1

+1为最简单的答案。我喜欢使用'filter_var'而不是'is_int',但这值得赞扬。 –