例如我有数组:
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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句