我正在尝试编写一种类似于该问题的最接近的数字代码块,只是我不希望我的代码返回任何大于指针的值。
基本上,您有一个值数组:
$array = array(2012, 2013, 2015, 2016, 2018);
该函数将具有这些结果
needle: 2011 result: 2012
needle: 2012 result: 2012
needle: 2014 result: 2013
我在考虑以下几点:
while(!in_array($year, $years))
{
if($year<$years[count($years)+1]){$year = $years[$count($years)+1];}//Edited
$year -= 1;
}
除非没有捕获到2011年的值小于数组中的所有值,否则
编辑,我想出了如何捕获2011年的例外,现在我唯一的问题是,如果说要输入3012年,php会经历大约1000次代码迭代,这似乎效率很低。
对于大型数组,您的代码示例可能会变得非常昂贵。最好避免多次遍历数组,这是in_array()在后台必须执行的操作。
试试这个:
function nearest(array $arr, $needle) {
$closest = current($arr);
foreach ($arr as $val) {
if ($val === $needle) {
return $val; // found it :)
}
if ($val > $closest && $val < $needle) {
// we found something closer and less than the needle, so use it
$closest = $val;
}
}
// we've reached the end, so return the closest solution
return $closest;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句