2012-04-15 6 views

Antwort

1

eine einfache, aber Brute-Force-Methode:

$distance = 1000000; // initialize distance as "far away" 
foreach ($array as $idx => $value) 
    if (abs ($idx - $target_index) < $distance) 
    { 
     $distance = abs ($idx - $target_index); 
     $best_idx = $idx; 
    } 
0

Wenn der Array-Schlüssel in Ordnung ist, können Sie einen effizienteren Algorithmus verwenden (die auf oder keinen spürbaren Unterschied machen abhängig, was das ist für und wie groß die Arrays sind):

$arr = [2 => 'a', 4 => 'b', 7 => 'c']; 
$input = 5; 

if (isset($arr[$input])) { 
    return $input; 
} 

foreach ($arr as $key => $value) { 
    if ($key > $input) { 
     if (prev($arr) === FALSE) { 
      // If the input is smaller than the first key 
      return $key; 
     } 
     $prevKey = key($arr); 

     if (abs($key - $input) < abs($prevKey - $input)) { 
      return $key; 
     } else { 
      return $prevKey; 
     } 
    } 
Verwandte Themen