Tay*_*Mac 20 php arrays arraylist
如果我有一个PHP数组:
$array
Run Code Online (Sandbox Code Playgroud)
有价值:
45,41,40,39,37,31
Run Code Online (Sandbox Code Playgroud)
我有一个变量:
$number = 38;
Run Code Online (Sandbox Code Playgroud)
我怎样才能返回值?:
39
Run Code Online (Sandbox Code Playgroud)
因为这是数组中最接近38(向上计数)的值?
问候,
泰勒
far*_*jad 24
<?php
function closest($array, $number) {
sort($array);
foreach ($array as $a) {
if ($a >= $number) return $a;
}
return end($array); // or return NULL;
}
?>
Run Code Online (Sandbox Code Playgroud)
小智 10
这是一个获得所需结果并适用于任何数组数据的高级过程:
O(n)
O(n lg n)
(希望如此)现在,假设数组按ASCENDING排序,这种方法可行:
O(n)
如果数组是DESCENDING(如在帖子中),请执行上述操作,但是:
O(n)
O(n lg n)
(希望如此)O(n)
快乐的编码.
在array_search上编辑拼写错误
哟...似乎很容易.这是一个功能
<?php
$array = array(45,41,40,39,37,31);
function closest($array, $number){
#does the array already contain the number?
if($i = array_search( $number, $array)) return $i;
#add the number to the array
$array[] = $number;
#sort and refind the number
sort($array);
$i = array_search($number, $array);
#check if there is a number above it
if($i && isset($array[$i+1])) return $array[$i+1];
//alternatively you could return the number itself here, or below it depending on your requirements
return null;
}
Run Code Online (Sandbox Code Playgroud)
跑步 echo closest($array, 38);
归档时间: |
|
查看次数: |
19853 次 |
最近记录: |