Hightest value of an associative array

2020-02-01 07:38发布

问题:

Is there any easy way to get the hightest numeric value of an associative array?

$array = array(
    0 => array(
        'key1' => '123',
        'key2' => 'values we',
        'key3' => 'do not',
        'key4' => 'care about'
    ),
    1 => array(
        'key1' => '124',
        'key2' => 'values we',
        'key3' => 'do not',
        'key4' => 'care about'
    ),
    2 => array(
        'key1' => '125',
        'key2' => 'values we',
        'key3' => 'do not',
        'key4' => 'care about'
    )
);

AwesomeFunction($array, 'key1'); // returns 2 ($array key)

Please be kind since this question was written with a phone. Thanks.

回答1:

If you know your data will always be in that format, something like this should work.

function getMax( $array )
{
    $max = 0;
    foreach( $array as $k => $v )
    {
        $max = max( array( $max, $v['key1'] ) );
    }
    return $max;
}


回答2:

PHP 5.5 introduced array_column() which makes this much simpler:

echo max(array_column($array, 'key1'));

Demo



回答3:

@ithcy - extension to that will work with any size array

function getMax($array) {
    if (is_array($array)) {
        $max = false;
        foreach($array as $val) {
            if (is_array($val)) $val = getMax($val);
            if (($max===false || $val>$max) && is_numeric($val)) $max = $val;
        }
    } else return is_numeric($array)?$array:false;
    return $max;
}

I think (returns false when there are no numeric values are found)



回答4:

This one is inspired by ithcy example, but you can set the key to look up. Also, it returns both the min and max values.

function getArrayLimits( $array, $key ) {
    $max = -PHP_INT_MAX;
    $min = PHP_INT_MAX;
    foreach( $array as $k => $v ) {
        $max = max( $max, $v[$key] );
        $min = min( $min, $v[$key] );
    }
    return Array('min'=>$min,'max'=>$max);
}


标签: php arrays