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


Find Array value ranges max and min value

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

output must be min=0;max=15
 Array
(
[0] => 5-10
[1] => 10-15
[2] => 0-2
[3] => 15
)
<?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);
?>

在数组上使用 PHP max()min() 函数,假设它在数组中设置值之前已经计算了这些值。

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

看起来像是使用 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;

试试这个...

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

您可以简单地使用 array_walk 以及 minmax 函数作为

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