php数组,输入一个值,并返回比他小的值

发布时间 2023-03-22 21:08:57作者: dangdemo
    function findClosestSmallerValue($array, $inputValue) {
        $minDifference = PHP_INT_MAX;
        $closestValue = null;
    
        foreach ($array as $value) {
            if ($value < $inputValue) {
                $difference = $inputValue - $value;
    
                if ($difference < $minDifference) {
                    $minDifference = $difference;
                    $closestValue = $value;
                }
            }
        }
    
        // 如果没有找到比输入值小的数,返回数组中最小的值
        if ($closestValue === null) {
            $closestValue = min($array);
        }
    
        return $closestValue;
    }


    public function test(){
        $array = [1, 3, 5, 10, 30, 80, 100];
        $inputValue = $this->request->post('num');

        $result = $this->findClosestSmallerValue($array, $inputValue);
        echo "输入 $inputValue 最小值: $result";
    }