代码之家  ›  专栏  ›  技术社区  ›  Industrial

PHP:从数组中获取两个最近的邻居?

  •  1
  • Industrial  · 技术社区  · 15 年前

    我发现 this thread 关于基于已知值从数组中选择最近/最近的值。如果有人想选 两个最近的值 从一个阵列看同样的说?

    $rebates = array(
       1 => 0,
       3 => 10,
       5 => 25,
      10 => 35)
    
    3 回复  |  直到 9 年前
        1
  •  2
  •   alex    15 年前
    $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
  •  2
  •   Jon    15 年前

    “最近的两个”是指两个小于或等于$items的值?

    不管怎样,从另一条线索的答案开始

    $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 ,但我觉得已经过头了。

        3
  •  0
  •   PeeHaa    15 年前
    $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)
    

    现在您有一个数组,数组中的所有项都与$retebes[5]的距离排序。所以你可以找到两个最接近的。 或者三个最近的。无论什么。

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

    推荐文章