如何在PHP中将范围数组合并到接近值?

时间:2018-03-14 18:09:32

标签: php arrays merge range

我在PHP中有一个范围数组,它不包含范围,但是我希望所有可能的范围都在接近值附近..!

范围数组如下:

$array = array('1.10','21.30','31.40','41.50','81.90');

我希望在marge之后如下:

$array = array('1.10','21.50','81.90');

我试图合并,但我想找出我没有的结果。

$dis  = array();
$array = array('1.10','21.30','31.40','41.50','81.90');

foreach ($array as $value) {
    $ex = explode('.',$value);

    if(isset($dis[$ex[1] + 1])){
        $dis[$ex[1] + 1][0] = $ex[0];
    }else if(isset($dis[$ex[0] - 10])){
        $dis[$ex[0] - 10][1] = $ex[1];
    }else $dis[$ex[0]] = $ex;
}

$new_array = array();
foreach($dis as $value){
    $new_array[] = implode('.',$value)
}

//Output : array('1.10','21.50','41.50','81.90')

这有什么简单的解决方案吗?

1 个答案:

答案 0 :(得分:0)

Yuu ...最后我做了这个ans并且工作正常......!

$dis  = array();
$array = array('121.130','101.110','31.40','61.70','1.10','21.30','51.60','81.90','111.120');
sort($array);
foreach($array as $value){
    $ex = explode('.',$value);
    $no = $ex[0] - 1;
    if(isset($dis[$no])){
        $dis[$ex[1]] = array($dis[$no][0],$ex[1]);
        unset($dis[$no]);
    }else $dis[$ex[1]] = $ex;
}
$new_array = array_map(function($v){ return implode('.',$v); }, $dis);