在数组中查找较高和较低的数字并存储在一个数组中

时间:2019-04-05 01:07:27

标签: php arrays

我需要获得与数字最接近的最低值和最高值。

尝试

<?php
    $a = array(1, 8, 23,42,47, 52, 55, 66, 74,75, 76,77,78, 95,);
    sort($a);
    $v = 58;    
    $lesser = null;
    $greater = null;
    foreach($a as $key => $current){
        if($current <= $v){
            $lesser     = $current;
            $greater    = $a[($key+1)];
        }else{

        }
    }
        print_r(array(
            "lesser"    => $lesser,
            "greater"   => $greater,
        ));  
?>
    /** output :
    Array 
   (
     lesser => 55
     greater => 66
    )
    **/

我的目标是使所有数字都大于给定数字,而较小的数字相同:

greater => 66, 74, 75, 77, 78, 95
lesser => 55, 52, 47, 42, 23, 8, 1

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

制作要推送到的$lesser$greater数组,而不是替换它们。

<?php
$a = array(1, 8, 23,42,47, 52, 55, 66, 74,75, 76,77,78, 95,);
$v = 58;    
$lesser = [];
$greater = [];
foreach($a as $key => $current){
    if ($current < $v) {
        $lesser[] = $current;
    } elseif ($current > $v) {
        $greater[] = $current;
    }
}
print_r(array(
    "lesser"    => $lesser,
    "greater"   => $greater,
));  
?>