Get min and max value in PHP Array

后端 未结 9 1825
天涯浪人
天涯浪人 2020-11-30 00:36

I have an array like this:


array (0 => 
  array (
    \'id\' => \'20110209172713\',
    \'Date\' => \'2011-02-09\',
    \'Weight\' => \'200\',
  ),
  1 =>          


        
相关标签:
9条回答
  • 2020-11-30 01:20

    It is interesting to note that both the solutions above use extra storage in form of arrays (first one two of them and second one uses one array) and then you find min and max using "extra storage" array. While that may be acceptable in real programming world (who gives a two bit about "extra" storage?) it would have got you a "C" in programming 101.

    The problem of finding min and max can easily be solved with just two extra memory slots

    $first = intval($input[0]['Weight']);
    $min = $first ;
    $max = $first ;
    
    foreach($input as $data) {
        $weight = intval($data['Weight']);
    
        if($weight <= $min ) {
            $min =  $weight ;
        }
    
        if($weight > $max ) {
            $max =  $weight ;
        }
    
    }
    
    echo " min = $min and max = $max \n " ;
    
    0 讨论(0)
  • 2020-11-30 01:21
    $num = array (0 => array ('id' => '20110209172713', 'Date' => '2011-02-09', 'Weight' => '200'),
              1 => array ('id' => '20110209172747', 'Date' => '2011-02-09', 'Weight' => '180'),
              2 => array ('id' => '20110209172827', 'Date' => '2011-02-09', 'Weight' => '175'),
              3 => array ('id' => '20110211204433', 'Date' => '2011-02-11', 'Weight' => '195'));
    
        foreach($num as $key => $val)   
        {                       
            $weight[] = $val['Weight'];
        }
    
         echo max($weight);
         echo min($weight);
    
    0 讨论(0)
  • 2020-11-30 01:22

    Option 1. First you map the array to get those numbers (and not the full details):

    $numbers = array_column($array, 'weight')
    

    Then you get the min and max:

    $min = min($numbers);
    $max = max($numbers);
    

    Option 2. (Only if you don't have PHP 5.5 or better) The same as option 1, but to pluck the values, use array_map:

    $numbers = array_map(function($details) {
      return $details['Weight'];
    }, $array);
    

    Option 3.

    Option 4. If you only need a min OR max, array_reduce() might be faster:

    $min = array_reduce($array, function($min, $details) {
      return min($min, $details['weight']);
    }, PHP_INT_MAX);
    

    This does more min()s, but they're very fast. The PHP_INT_MAX is to start with a high, and get lower and lower. You could do the same for $max, but you'd start at 0, or -PHP_INT_MAX.

    0 讨论(0)
提交回复
热议问题