Hightest value of an associative array

一曲冷凌霜 提交于 2019-11-26 22:03:54

问题


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);
}


来源:https://stackoverflow.com/questions/5093171/hightest-value-of-an-associative-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!