以递归方式转换我的脚本?

时间:2015-12-28 08:19:07

标签: php recursion

我有搜索最近搜索号码的脚本。 例如,假设在数组中是这个数字:

'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);

但我得到空白页甚至我转储功能输出。

2 个答案:

答案 0 :(得分:1)

//$a is array to be searched
//$s is search key
//$prev_key and $next_key will be output required

$a = array('0'=>1,'0.25'=>123,'0.75'=>456,'0.78'=>456,'1'=>788);
$s = '0';

if(isset($a[$s])){
    echo $s;
}
else{

    reset($a);//good to do

    while(key($a) < $s){ 
        next($a);
    }

    $next_key = key($a);
    prev($a);
    $prev_key = key($a);

    echo $prev_key.'-'.$next_key;
}

上面的代码使用数组内部指针。我想这可能对你有帮助..

来源:https://stackoverflow.com/a/4792770/3202287

答案 1 :(得分:1)

使用array_map函数,

$data = array('0'=>1.72,'0.75'=> 2.35,'0.25'=>1.92,'1' => 3.00);
$v = 0.5; // search value 

$x = null; // difference value
$y = array(); // temporary array
array_map(function($i)use($data,$v,&$x,&$y){
    if(isset($x)){
        if($x > abs($i-$v)){ // if difference value is bigger than current
            $x = abs($i-$v);
            $y = array($i=>$data[$i]);
        }else if($x == abs($i-$v)){ // if difference value is same
            $key = array_keys($y);
            $y = $key[0] < $i ? array($i=>$data[$i]) : $y;
        }
    }else{ // first loop
        $x = abs($i-$v);
        $y = array($i=>$data[$i]);
    }
},array_keys($data));
print_r($y); // result

输出Array ( [0.75] => 2.35 ),希望对您有帮助。

相关问题