【发布时间】:2015-12-28 08:19:06
【问题描述】:
我有搜索最接近搜索号码的脚本。 例如,假设数组中有这个数字:
'0' => 1.72
'0.25' => 1.92
'0.75'=> 2.35
'1' => 3.00
我正在寻找 0.50 的让分盘,所以 0.25 和 0.75 在 0.50 的相同范围内。
在这种情况下,我想获得更大的数字,在这个例子中是 0.75。
有效的代码是这样的:
function getClosest($search, $arr) {
$closest = null;
$num_arr = array();
$odd = 0.00;
$i = 0;
foreach ($arr as $handicap=>$item) { //first closest number
if ($closest === null || abs($search - $closest) > abs($handicap - $search)) {
$closest = $handicap;
$odd = $item;
}
else{
$num_arr[$handicap] = $item;
}
}
$newclosest = null;
$newodd = 0.00;
foreach($num_arr as $handicap=>$newitem){ //second closest number
if ($newclosest === null || abs($search - $closest) > abs($handicap - $search)) {
$newclosest = $handicap;
$newodd = $newitem;
}
}
//if difference between first and second number are same
if(abs($search - $closest) == abs($newclosest - $search)){
if($newclosest > $closest){ //if second number is greater than first
$closest = $newclosest;
$odd = $newodd;
}
}
return array('handicap'=>$closest,'odd'=>$odd);
}
我看到我可以在这里使用递归,但我没有使用递归的经验。我知道我需要像这样在里面调用它:
$rec_arr = getClosest($num_arr,$search);
但即使我转储函数输出,我也会得到空白页。
【问题讨论】:
-
我还没有正确检查它,但是您在函数调用中错误定位了参数