在循环

时间:2015-09-29 10:22:15

标签: php numbers closest

我有一个数组。给定一个数字X(不得包含在数组中),我想在一个循环中搜索数组中下一个较大和较低数量的X.我的代码是:

<?php
  $a = array(1, 8, 23, 25, 40,41,42,47, 52, 55, 66, 74,75, 76,77,78, 95, 102,103, 104, 105,106, 126, 128, 140, );
  $v = 104;
  sort($a);
  $nearestGreater = null;
  $nearestLower = null;
  foreach ($a as $key => $val) {
    if ( $v<=$val) {
      $nearestGreater = (isset($a[$key + 1])) ? $a[$key + 1]: $nearestGreater;
      $nearestLower = (isset($a[$key - 1])) ? $a[$key - 1]: $nearestLower;
      break;
    }
  }
  var_dump($nearestLower);
  echo "<br/>".$v."<br/>";
  var_dump($nearestGreater);
  unset($a);
?>    

2 个答案:

答案 0 :(得分:0)

使用代码块

以干净可读的方式编写代码
$nearestGreater=null;
$nearestLower = null;
 $a = array(1, 8, 23, 25, 40,41,22,47, 52, 55, 66, 74,75, 76,77,78, 95, 102,103, 104, 105,106, 126, 128, 140, );
 $v = 104; 
foreach( $a as $val)
  {
     if($val < $v)
          { 
              if(isset($nearestLower))
                {    if($nearestLower < $val)
                      $nearestLower=$val;
                }
                  else
                { 
                       $nearestLower=$val;
               }
          }

             if($val > $v)
          { 
              if(isset($nearestGreater))
                {    if($nearestGreater > $val)
                      $nearestGreater=$val;
                }
                  else
                { 
                       $nearestGreater=$val;
               }
          }
  }

答案 1 :(得分:0)

试试这个:

&GT;

<?php
    $a = array(1, 8, 23, 25, 40,41,42,47, 52, 55, 66, 74,75, 76,77,78, 95, 102,103, 104, 105,106, 126, 128, 140, );
    sort($a);
    $v = 58;    
    $lesser = null;
    $greater = null;
    foreach($a as $key => $current){
        if($current <= $v){
            $lesser     = $current;
            $greater    = $a[($key+1)];
        }else{

        }
    }
    echo "<pre>";
        print_r(array(
            "lesser"    => $lesser,
            "greater"   => $greater,
        ));
    echo "</pre>";   
?>

编辑后,即使比赛有两个更高,也更高

<?php
    $allNumbers = array(1, 8, 23, 25, 40,41,42,47, 52, 55, 66, 74,75, 76,77,78, 95, 102,103, 104, 105,106, 126, 128, 140, );
    sort($allNumbers);
    $input = 55;
    $index = array_search($input, $allNumbers);
    if(empty($index)){
        foreach($allNumbers as $key => $value){
            if($value < $input){
                $index = ($key + 0.5);
            }else{
                break;
            }
        }
    }
    $below = array(
        $allNumbers[ceil($index - 2)],
        $allNumbers[ceil($index - 1)],
    );

    $above = array(
        $allNumbers[floor($index + 1)],
        $allNumbers[floor($index + 2)],
    );

    echo "<pre>";
    print_r(array(
        "input" => $input,
        "index" => $index,
        "below" => $below,
        "above" => $above,
    ));
    echo "</pre>";
?>