【问题标题】:How to find the best matching key in a PHP array如何在 PHP 数组中找到最佳匹配键
【发布时间】:2012-04-27 03:47:47
【问题描述】:

我在 php 中有一个关联数组。键是整数。如何找到与任何整数输入最近的键?

【问题讨论】:

  • 当有两个最近的键时会发生什么。
  • 没有考虑到这一点。需要弄清楚。

标签: php arrays


【解决方案1】:

一个简单但蛮力的方法:

$distance = 1000000;  // initialize distance as "far away"
foreach ($array as $idx => $value)
   if (abs ($idx - $target_index) < $distance)
   {
      $distance = abs ($idx - $target_index);
      $best_idx = $idx;
   }

【讨论】:

    【解决方案2】:

    如果数组键是有序的,您可以使用更有效的算法(这可能会或可能不会产生明显的差异,具体取决于它的用途和数组的大小):

    $arr = [2 => 'a', 4 => 'b', 7 => 'c'];
    $input = 5;
    
    if (isset($arr[$input])) {
        return $input;
    }
    
    foreach ($arr as $key => $value) {
        if ($key > $input) {
            if (prev($arr) === FALSE) {
                // If the input is smaller than the first key
                return $key;
            }
            $prevKey = key($arr);
    
            if (abs($key - $input) < abs($prevKey - $input)) {
                return $key;
            } else {
                return $prevKey;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      • 2011-09-23
      • 1970-01-01
      • 2018-12-29
      • 2011-12-22
      • 1970-01-01
      • 2015-09-24
      相关资源
      最近更新 更多