问题描述
请问有内置函数可以使用PHP获取最接近的N个特定数字的数字吗?我的意思是,例如,我们有数字5
。现在,我需要获得一个像[3,4,5,6,7]
这样的数组。
因此,我正在寻找某个函数nearestNumbers(5,2)
,其中5
-特定数字,而2
-向上/向下转换为特定数字的数量,其作用为{{1 }}。谢谢!
实际上,当使用带有自定义[3,7]
的Laravel分页时,这看起来真的很奇怪:
$elements
解决方法
内置函数最好的功能可能是range
:
range( $paginator->currentPage()-2,$paginator->currentPage()+2 )
您可以这样编写一个辅助函数:
function nearestNumbers( $x,$d ) {
return range( $x - $d,$x + $d );
}
您可以使用min
和max
来限制范围:
function nearestNumbers( $x,$d,$lim ) {
return range( max( $x - $d,1 ),min( $x + $d,$lim ) );
}