从包含正整数和/或递归嵌套正整数数组的数组中查找最大值

时间:2012-08-22 04:17:16

标签: php arrays max

如果数组初始化为:

   $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;   
}

2 个答案:

答案 0 :(得分: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值。

答案 1 :(得分: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;
}