PHP:从阵列中两个最近的邻居? [英] PHP: Get two nearest neighbors from array?

查看:127
本文介绍了PHP:从阵列中两个最近的邻居?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现<一个href=\"http://stackoverflow.com/questions/4032753/picking-the-nearest-value-from-an-array-reflecting-ranges\">this螺纹有关从基于已知值的数组挑选最接近/最接近的值。那么如果一个人想挑两个最近从阵列中寻找相同的值说呢?

  $回扣=阵列(
   1 =&GT; 0,
   3 =&GT; 10,
   5 =&GT; 25,
  10 =&GT; 35)


解决方案

  $回扣=阵列(
   1 =&GT; 0,
   3 =&GT; 10,
   5 =&GT; 25,
  10 =&GT; 35);
功能getArrayNeighborsByKey($数组$ findKey){    如果(!array_key_exists($阵列,$ findKey)){
        返回FALSE;
    }    $选择= $prevous = $下一= NULL;    的foreach($数组$关键=&GT; $值){
        $ thisValue =阵列($关键=&GT; $值);
        如果($关键=== $ findKey){
           $选择= $ thisValue;
           继续;
        }
        如果($选择!== NULL){
            接下来$ = $ thisValue;
            打破;
        }
        $previous = $ thisValue;    }   返回阵列(
            'preV =&GT; $previous,
            当前= GT; $选择,
            '下一个'=&GT;接下来$
    );}

看看吧!

I found this thread about picking the closest/nearest value from an array based upon a known value. What about if one wants to pick the two nearest values from an array looking at the same say?

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

解决方案

$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!

这篇关于PHP:从阵列中两个最近的邻居?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆