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

レコードをループした後、優先順位が , , , , , ... であるため、キーが必要な値を 1 つだけ取得する必要があり123Dます 。123D123P123DD123PP123DDD123PPP123PPPP

例:

  • 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

この関数は簡単に整理できますが、これは再帰で解決できるものです。これは123D、 が配列内にある場合、コードが高度に最適化され、 の場合は 1 回、 の場合は 2 回、 の123P場合は 3 回などだけ実行されることを意味します123DD

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 に答える
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 に答える