查找数组值范围最大值和最小值

时间:2015-06-19 11:22:54

标签: php arrays

这是我的数组如何找到最小值和最大值。即,

output must be min=0;max=15

 Array
(
[0] => 5-10
[1] => 10-15
[2] => 0-2
[3] => 15
)

7 个答案:

答案 0 :(得分:1)

<?php 
$price_range=array("0-2","2-5","5-10","10-15","15");
foreach($price_range as $key=>$value){
$a=explode('-',$value);
if($a[0] != ''){$b[]= $a[0];}
if($a[1] != ''){$b[]= $a[1];}
}
echo 'min: '.$min=min($b);
echo 'max: '.$max=max($b);
?>

答案 1 :(得分:0)

在数组上使用PHP max()min()函数,假设在将值设置到数组之前已经对它进行了计算。

答案 2 :(得分:0)

遍历数组并检查索引或使用php中的min()/ max()函数

答案 3 :(得分:0)

看起来像是使用array_reduce()

的主要候选人
$price_range = ["0-2","2-5","5-10","10-15","15"];

$min = array_reduce(
    $price_range,
    function ($carry, $value) {
        return min(array_merge(explode('-',$value), [$carry]));
    },
    PHP_INT_MAX
);

$max = array_reduce(
    $price_range,
    function ($carry, $value) {
        return max(array_merge(explode('-',$value), [$carry]));
    },
    -PHP_INT_MAX
);

echo 'min: '.$min, PHP_EOL;
echo 'max: '.$max, PHP_EOL;

答案 4 :(得分:0)

试试这个...

$price=array();
$price_range=array("0-2","2-5","5-10","10-15","15");
foreach($price_range as $key=>$value){
$a=explode('-',$value);
array_push($price,$a[0]);
}
echo 'min: '.$min=min($price);
echo 'max: '.$max=max($price);

答案 5 :(得分:0)

$input_range = ['0-2','2-5','5-10','10-15','15'];

$collect = [];

foreach($input_range as $range)
{
    $collect = array_merge($collect, explode('-', $range));
}

$min = min($collect);
$max = max($collect);

答案 6 :(得分:0)

您只需将array_walkminmax函数一起使用

即可
$price_range = array("0-2","2-5","5-10","10-15","15");
$result = array();
array_walk($price_range,function($v,$k)use(&$result){ 
    $result = array_merge($result,explode('-', $v));
});
echo "Min value = ".min($result)." & Max value = ".max($result);