dsa5211314 2012-06-26 15:45
浏览 11
已采纳

查找最接近变量的值的数组名称?

I am attempting to find the closest product to the given budget

$array = array(
    'productname1' => 5,
    'productname2' => 10,
    'productname3' => 15
)

$budget = 12;

I have tried using a function like the following to find the nearest value, but it only returns the number which is closest to the budget rather than the product name.

   function closest($array, $number) {
        sort($array);
        foreach ($array as $a) {
            if ($a >= $number) return $a;
        }
        return end($array);
    }

I can't help but think there is a MUCH better implementation of this. Any help would be much appreciated.

  • 写回答

4条回答 默认 最新

  • duanrong6802 2012-06-26 15:57
    关注
    foreach($array as $k => $v){ $diff[abs($v - $budget)] = $k; }
    ksort($diff, SORT_NUMERIC);
    $closest_key = current($diff);
    
    var_dump($closest_key);         // Product Name
    var_dump($array[$closest_key]); // Product Cost
    

    Prints:

        string(12) "productname2"
        int(10)
    

    Or as a function:

    function closest($array, $price)
    {
        foreach($array as $k => $v){ $diff[abs($v - $price)] = $k; }
        ksort($diff, SORT_NUMERIC);
        $closest_key = current($diff);
        return array($closest_key, $array[$closest_key]);
    }
    
    print_r(closest($array, $budget));
    

    Prints:

        Array
        (
            [0] => productname2  // Product Name
            [1] => 10            // Product Price
        )
    

    Both formats include only three steps:

    • Calculate the difference between the product cost and the budget
    • Sort these
    • Take the first element from the sorted array (the element whose price is closest to the budget).

    EDIT: If you don't care about anything other than the single closest product, then a sort is overkill and a simple min() function (like Emil used) would be a lot faster. For example:

    function closest($array, $price)
    {
        foreach($array as $k => $v){ $diff[abs($v - $price)] = $k; }
        $closest_key = $diff[min(array_keys($diff))];
        return array($closest_key, $array[$closest_key]);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应