2010-11-25 101 views

回答

2
$rebates = array(
    1 => 0, 
    3 => 10, 
    5 => 25, 
    10 => 35); 


function getArrayNeighborsByKey($array, $findKey) { 

    if (! array_key_exists($array, $findKey)) { 
     return FALSE; 
    } 

    $select = $prevous = $next = NULL; 

    foreach($array as $key => $value) { 
     $thisValue = array($key => $value); 
     if ($key === $findKey) { 
      $select = $thisValue; 
      continue; 
     } 
     if ($select !== NULL) { 
      $next = $thisValue; 
      break; 
     } 
     $previous = $thisValue; 

    } 

    return array(
      'prev' => $previous, 
      'current' => $select, 
      'next' => $next 
    ); 

} 

See it!

2

通过 “两个最近的” 你的意思是两个小于或等于$物品价值?

总之,从这个问题的答案其他线程,这是

$percent = $rebates[max(array_intersect(array_keys($rebates),range(0,$items)))]; 

开始你可以去

$two_nearest = array_slice(array_intersect(array_keys($rebates),range(0,$items)), -2); 
$most_near = $rebates[$two_nearest[1]]; 
$less_near = $rebates[$two_nearest[0]]; 

这或许可以减少使用array_map的一行代码,但我认为它已经过了。

0
$rebates = array(
    1 => 0, 
    3 => 10, 
    5 => 25, 
    10 => 35) 

$distances = array(); 
foreach($rebates as $key=>$item) { 
    if ($key == 5) continue; 
    $distances = abs($rebates[5] - $item); 
} 

sort($distances, SORT_NUMERIC) 

现在你有一个数组中的所有项目,它们的距离为$ rebates [5]排序。所以你可以得到最接近的两个。 或三个最接近的。随你。

请记住,2个项目可以有相同的距离。

+0

条件需要包装在括号`(`&`)`中。 – alex 2010-11-25 23:47:08