PHP 需要一个函数来从对象中获取最接近的数字

PHP Need a function to get closest number out of a object

我有以下代码

function closestdown($array, $number) {

                                  sort($array);
                                    foreach ($array as $a) {
                                        if ($a->stappen <= $number){
                                            return $a;
                                    }}
                                    return end($array); // or return NULL;
                                }

我这样称呼它:

$citylist = $manager->getStedenList();            
$stappeng = $user->user_stappen;    
$lowernumber = closestdown($citylist, $currentcity);

但它没有给我最接近的数字,而是 return 它遇到的第一个较小的数字。

示例:如果我使用这些数字

$lowernumber = closestdown(1 5 6 99 487 98785, 100);

它 returns : 1 而它应该 return 99.

$citylist 看起来像:

array(4) {
  [0]=>
  object(Steden)#272 (3) {
    ["name"]=>
    string(10) "Bourguette"
    ["id"]=>
    string(1) "6"
    ["stappen"]=>
    string(2) "13"
  }
  [1]=>
  object(Steden)#268 (3) {
    ["name"]=>
    string(4) "Gent"
    ["id"]=>
    string(1) "4"
    ["stappen"]=>
    string(3) "666"
  }
  [2]=>
  object(Steden)#271 (3) {
    ["name"]=>
    string(16) "garabier(Afrika)"
    ["id"]=>
    string(1) "8"
    ["stappen"]=>
    string(9) "909814037"
  }
  [3]=>
  object(Steden)#297 (3) {
    ["name"]=>
    string(9) "Terneuzen"
    ["id"]=>
    string(1) "7"
    ["stappen"]=>
    string(10) "2147483647"
  }
}

如何获得最接近 $stappeng 的数字(它仅包含 1 个值示例:“100”)

提前致谢

function closestdown($array, $number) {
     sort($array);
     $closest = 1000000000000;
     $return = null;
     foreach ($array as $a) {
          if (abs($a->stappen - $number) < $closest && $a->stappen <= $number){
              $closest = abs($a->stappen - $number);
              $return = $a;
     }}
     return $return ; 
}

您的函数返回了第一个值。

$closest = NULL;
foreach ($array as $a) {
    if ($a->stappen <= $number) {
        $closest = $a;
    }
    else /* if ($a->stappen > $number) */ {
        return $closest;
    }
}
...

你需要在循环中改变一些东西

<?php
    function closestdown($array, $number) {
      if(count($array)==1){
        return $array[0];
      }
      sort($array);
        foreach ($array as $a) {
            if ($a > $number){//You can use $a->stappen 
                if(($a-$number)<($number-$previous))
                  return $a;
                else
                  return $previous;
            }else{
              $previous = $a;
            }                                        
        }
        return end($array); // or return NULL;
    }
    echo $lowernumber = closestdown([1, 5, 6, 99, 487, 98785], 100);
?>

查看演示:https://eval.in/698262

请使用这个..

<?php

$array = array(1,4,5,90,99,102,104);
$number = 100;

echo closestdown($array,$number);

function closestdown($array, $number) {

//sort($array);
$temp = array();
foreach ($array as $a) {

    array_push($temp,abs($a-$number));

}
asort($temp);
return $array[key($temp)];
}

?>