如何编写函数Max($ array),它返回$ array中包含的最大值或嵌套在$ array中的一些数组

如何编写函数Max($ array),它返回$ array中包含的最大值或嵌套在$ array中的一些数组

问题描述:

Eg:

$array= array(array(141,151,161),2,3,array(101,202,array(303,606)));

output :606

例如: p>

  $ array = array(array(141,151,161)  ),2,3,数组(101,202,数组(303,606))); 
  code>  pre> 
 
 

输出:606 p> div>

Same idea as Pascal's solution, only shorter thanks to the Standard PHP Library

$arr= array(array(141,151,161),2,3,array(101,202,array(303,404)));
echo rmax($arr);

function rmax(array $arr) {
  $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
  // initialize $max
  $it->next(); $max = $it->current();
  // "iterate" over all values
  foreach($it as $v) {
    if ( $v > $max ) {
      $max = $v;
    }
  }
  return $max;
}

What you need is to recursively go through your array ; which means the max function, which is not recursive, will not be "enough".

But, if you take a look at the users's notes on the manual page of max, you'll find this note from tim, who proposes this recursive function (quoting) :

function multimax( $array ) {
    // use foreach to iterate over our input array.
    foreach( $array as $value ) {

        // check if $value is an array...
        if( is_array($value) ) {

            // ... $value is an array so recursively pass it into multimax() to
            // determine it's highest value.
            $subvalue = multimax($value);

            // if the returned $subvalue is greater than our current highest value,
            // set it as our $return value.
            if( $subvalue > $return ) {
                $return = $subvalue;
            }

        } elseif($value > $return) {
            // ... $value is not an array so set the return variable if it's greater
            // than our highest value so far.
            $return = $value;
        }
    }

    // return (what should be) the highest value from any dimension.
    return $return;
}

Using it on your array :

$arr= array(array(141,151,161),2,3,array(101,202,array(303,404)));
$max = multimax($arr);
var_dump($max);

Gives :

int 404

Of course, this will require a bit more testing -- but it should at least be a start.


(Going through the users' notes on manual pages is always a good idea : if you're having a problem, chances are someone else has already had that problem ;-) )

A more elegant solution:

function MaxArray($arr)
{
    function findMax($currentValue, $currentKey)
    {
        global $maxValue;
        $maxValue = ($currentValue > $maxValue ? $currentValue : $maxValue);
    }
    array_walk_recursive($arr, 'findMax');
    return $GLOBALS['maxValue'];
}

http://www.java2s.com/Code/Php/Data-Structure/FindtheMaximumValueinaMultidimensionalArray.htm

function recursive_array_max($a) {
    foreach ($a as $value) {
        if (is_array($value)) {
            $value = recursive_array_max($value);
        }
        if (!(isset($max))) {
            $max = $value;
        } else {
            $max = $value > $max ? $value : $max;
        }
    }
    return $max;
}
$dimensional = array(
    7,
    array(3, 5),
    array(5, 4, 7, array(3, 4, 6), 6),
    14,
    2,
    array(5, 4, 3)
    );

$max = recursive_array_max($dimensional);

Finding the max avoiding too much recursion :

function array_max(array $array) {
    $context = func_get_args();
    $max = -INF;

    while (!empty($context)) {
        $array = array_pop($context);
        while (!empty($array)) {
            $value = array_pop($array);
            if (is_array($value)) {
                array_push($context, $value);
            }
            elseif ($max < $value) {
                $max = $value;
            }
        }
    }

    return $max;
}

A more general method avoiding too much recursion :

function array_reduce_recursive($default, array $array, $callback = null) {
    $context = func_get_args();
    $count = func_num_args();
    if (is_callable(func_get_arg($count - 1))) {
        $callback = array_pop($context);
    }
    else {
        $callback = create_function('$x, $y', 'return $x < $y ? $y : $x;');
    }
    $reduced = array_shift($context);

    while (!empty($context)) {
        $array = array_pop($context);
        while (!empty($array)) {
            $value = array_pop($array);
            if (is_array($value)) {
                array_push($context, $value);
            }
            else {
                $reduced = $callback($reduced, $value);
            }
        }
    }

    return $reduced;
}

function array_max_recursive() {
    $args = func_get_args();
    $callback = create_function('$x, $y', 'return $x < $y ? $y : $x;');
    return array_reduce_recursive(-INF, $args, $callback);
}

By this way you can specify the callback method if you are looking for something else than the biggest number. Also this method takes several arrays.

The end way is less efficient of course.

With this you have a full compatibility with lot of PHP version.

$arr = array(array(141,151,161), 2, 3, array(101, 202, array(303,404)));
$callback = function ($value, $key) use (&$maximo) {
    if( $value > $maximo){
        $maximo = $value;
    }
};
array_walk_recursive($arr, $callback);
echo '<pre>'; print_r($maximo);``

function MaxArray($arr) {
    $maximum = 0;
    foreach ($arr as $value) {
        if (is_array($value)) {
            //print_r($value);
            $tmaximum = MaxArray($value);
            if($tmaximum > $maximum){
                $maximum = $tmaximum;
            }
        }
        else
        {
            //echo $value.'
';
            if($value > $maximum){
                $maximum = $value;
            }
        }
    }
    return $maximum;
}

It's very simple

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$max = max(iterator_to_array($iterator, false));