例如,我输入array:
Array(
[0] => 15
[1] => 6
[2] => 19
[3] => 21
[4] => 18
)
如果当前时间是20,那么我需要值19(小于并接近20)
同样,如果我传递X数为17,它将从数组返回15。
如果是7,那么它应该返回6。
请建议如何实现与PHP?
谢谢!
您可以使用array_filter
和end
函数创建您的自定义函数,如
function find_closest($arr,$x){
sort($arr);
$filtered_array = array_filter($arr,function($v)use($x){
return $v < $x;
});
return count($filtered_array) > 0 ? end($filtered_array) : "Your Message";
}
echo find_closest($arr,17);
我会这样做。我认为这比公认的答案(
)更简洁(可能更快)。function closest($arr, $x) {
$result = "default";
sort($arr);
foreach($arr as $value) {
if($value < $x) {
$result = $value;
} else
break;
}
return $result;
}
将要查找的元素Push到数组中。
array_push($your_array, "17");
$arr = asort($your_array);
$key = array_search('17', $arr);
的值将在 arr美元(键1美元)。