简体   繁体   English

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

[英]Finding maximum value from an array which contains positive integers and/or recursively nested arrays of positive integers

If an array initialized as: 如果数组初始化为:

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

Then the result should be: 100000 那么结果应该是:100000

I have written a function to solve this problem but I need less bytes and less memory of codes. 我已经编写了一个函数来解决此问题,但是我需要更少的字节和更少的代码存储空间。

My Function is: 我的职能是:

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

Taken from PHP manual but authored by me: 取自PHP手册,但由我撰写:

/**
 * @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;
}

  • This function is not actually recursive, but fulfills the requirement that it works on sub-arrays. 该函数实际上不是递归的,但是可以满足其在子数组上工作的要求。 I enjoy doing things without the runtime stack from time to time. 我喜欢不时使用运行时堆栈来做事。
  • It returns something of type int, never a string representation of an int. 它返回int类型的内容,从不返回int的字符串表示形式。 The exception is when you provide an array that does not contain any integers. 当您提供不包含任何整数的数组时,情况就是例外。 It will then return NULL. 然后它将返回NULL。
  • It ignores non-array, non-int values. 它忽略非数组,非整数值。

A handy function for walking over nested arrays is array_walk_recursive() . 用于遍历嵌套数组的便捷函数是array_walk_recursive() It means that you don't have to worry about the handling the recursion yourself and can get on with the task at hand, in this case finding the maximum value. 这意味着您不必担心自己要处理递归,并且可以继续进行手头的任务,在这种情况下,可以找到最大值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM