1
$records = array(
 '123PP' => 3.63,
 '123DDD' => 9.63,
 '123D' => 6.63,
 '123PPPP' => 9.63,
 '123DD' => 9.63,
 '123P' => 2.63,
 '123PPP' => 1.53
); 

遍历记录后,我只需要得到一个键应该是123D的值,因为优先顺序是: 123D, 123P, 123DD, 123PP, 123DDD, 123PPP, 123PPPP...

例如:

  • 如果123D在数组中没有找到,那么123P就是答案。
  • 如果123P在数组中没有找到,那么123DD就是答案。

我找到了一个解决方案:

foreach ($records as $key => $value) {
if (empty($this->minLength)) {
$this->invoiceTax = $value;
          $this->minLength = strlen($key);
        }
        elseif (strpos($key, 'P') !== false && (strlen($key) < $this->minLength)) {
          $this->invoiceTax = $value;
          $this->minLength = strlen($key);
        }
        elseif (strpos($key, 'D') !== false && (strlen($key) <= $this->minLength)) {
          $this->invoiceTax = $value;
          $this->minLength = strlen($key);
        }

但我想知道是否可以通过不存储每个键的字符串长度来优化这段代码。

4

2 回答 2

0
function prepareFunctionCall(){
  $records = array('123PP' => 3.63,'123DDD' => 9.63,'123PPPP' => 9.63
  ,'123DD' => 9.63,'123P' => 2.63,'123PPP' => 1.53); 

  // '123D' => 6.63,
  foreach($records as $key=>$value){
    $tmp = strlen($key).$key;
    $arTmp[$tmp] = $value;
  }
  getFirstValue($arTmp);
}

function getFirstValue($pArray){
  ksort($pArray);
  reset($pArray);
  print key($pArray).' = '.current($pArray);
}

这是 MatthewMcGovern 提供的良好解决方案的替代方案。

我提供了替代方案,因为这个函数使用了 php 函数 ksort、reset 和 current。这些函数是为这种情况创建的,如果可能的话,我建议您在找出哪个键是要选择的第一个键之前重写数组的键。这就是我添加 strlen 所做的。但与在收集数据时重写密钥相比,这是次优的。该函数的核心是对函数 ksort、reset 和 current 的调用。

于 2013-05-15T09:53:09.190 回答
0

这个函数可以很容易地整理,但这可以通过递归来解决。这意味着如果123D在数组中,代码将被高度优化,并且只运行一次、两次 for 123P、三次 for123DD等。

function GetMostPref($records, $key = "123", $next = "D", $depth = 0)
{
   if($depth == count($records))
   {
       // Hit end of array with nothing found
       return false;
   }

   if(strpos($next, 'D') !== false)
   {
     // Currently looking at a 'D...' key.
     // Next key is the same length as this key just with Ps.
     $nextKey = str_repeat('P', strlen($next));
   }
   else if(strpos($next, 'P') !== false)
   {
     // Currently looking at a 'P...' key.
     // Next key has one extra char and is all Ds.
     $nextKey = str_repeat('D', strlen($next)+1);
   }
   else
   {
       // Key not valid
       return false;
   }

   if(array_key_exists($key.$next, $records))
   {
      // Found the key in the array so return it.
      return $records[$key.$next];
   }
   else
   {
      // Recursive call with the next key and increased depth.
      return GetMostPref($records, $key, $nextKey, $depth + 1);
   }
}


// Testing
$records = array(
 '123PP' => 3.63,
 '123DDD' => 9.63,
 '123D' => 6.63,
 '123PPPP' => 9.63,
 '123DD' => 9.63,
 '123P' => 2.63,
 '123PPP' => 1.53
);

// Finds 123D and returns 6.63
echo GetMostPref($records);
于 2013-05-15T09:08:29.800 回答