0

I have script who searches closest searched number. So for example, let say that in array are this numbers:

'0' => 1.72

'0.25' => 1.92

'0.75'=> 2.35

'1' => 3.00

I am searching for 0.50 handicap, so 0.25 and 0.75 are in same range from 0.50.

In this situations i want to get greater number, what is 0.75 in this example.

Code what works is this:

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

I see that i can use recursion here, but i am not experienced in using recursion. I know that i need call it inside like this:

$rec_arr = getClosest($num_arr,$search);

but i get blank page even i dump function output.

user1814358
  • 619
  • 3
  • 8
  • 17

2 Answers2

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;
}

The above code uses array internal pointers. I think this may help you..

source: https://stackoverflow.com/a/4792770/3202287

Community
  • 1
  • 1
narasimharaosp
  • 533
  • 3
  • 12
1

use array_map function,

$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

output Array ( [0.75] => 2.35 ), hope this help you.

check
  • 559
  • 4
  • 12