[英]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;
}
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.