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"; }
标签:minDifference,difference,closestValue,value,inputValue,数组,array,php,输入 From: https://www.cnblogs.com/dq2758/p/17239026.html