如果数组初始化为:
$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))));
Run Code Online (Sandbox Code Playgroud)
那么结果应该是: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;
}
Run Code Online (Sandbox Code Playgroud)
摘自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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1997 次 |
| 最近记录: |