PHP从数组中获得最高值和最低值

时间:2014-07-18 13:00:23

标签: php arrays

我有一个像这样的数组:

Array
(
    [0] => Array
        (
            [rb_priceRangeId] => 3
            [rb_priceRangeMin] => 300000
            [rb_priceRangeMax] => 399999
        )

    [1] => Array
        (
            [rb_priceRangeId] => 5
            [rb_priceRangeMin] => 400000
            [rb_priceRangeMax] => 499999
        )

)

如何将rb_priceRangeMin中的最低值输入变量并从rb_priceRangeMax中获取最高值到变量中?我想我必须使用foreach,但我不知道它会在里面发生什么。任何帮助都将受到高度赞赏

我试过了

foreach($array as $row => $value){

$min = $value['rb_priceRangeMin'];

if($min < $value['rb_priceRangeMin']){
     $min = $value['rb_priceRangeMin'];
}

$max = $value['rb_priceRangeMax'];

if($max < $value['rb_priceRangeMax']){
     $max = $value['rb_priceRangeMax'];
}

} 

2 个答案:

答案 0 :(得分:1)

$minmax = array('min' => $array[0]['rb_priceRangeMin'], 'max' => 0);
foreach ($array as $val) {
    if ($val['rb_priceRangeMin'] < $minmax['min']) { $minmax['min'] = $val['rb_priceRangeMin']; }
    if ($val['rb_priceRangeMax'] > $minmax['max']) { $minmax['max'] = $val['rb_priceRangeMax']; }
}

答案 1 :(得分:1)

$minValue = false;
$maxValue = false;

foreach( $array as $a )
{
    if ( $minValue === false || $a['rb_priceRangeMin'] < $minValue ) $minValue = $a['rb_priceRangeMin'];
    if ( $maxValue === false || $a['rb_priceRangeMax'] > $maxValue ) $maxValue = $a['rb_priceRangeMax'];
}