2010-05-23 6 views
3

배열 두통이 계속 발생합니다. 이 함수는 내가 원하는 것을 수행하지만, 아직 PHP : s array/looping 함수에 익숙하지 않기 때문에 퍼포먼스 관점에서 개선 될 수있는이 함수의 부분이 있다면 내 질문이 그 것이다.PHP 수정 및 배열 조합

$var = myFunction (array('key1', 'key2', 'key3', '111')); 

function myFunction ($keys) { 
    $prefix = 'prefix_'; 

    $keyCount = count($keys); 

    // Prefix each key and remove old keys 
    for($i=0;$i<$keyCount; $i++){ 
     $keys[] = $prefix.$keys[$i]; 
     unset($keys[$i]); 
    } 
    // output: array('prefix_key1', 'prefix_key2', 'prefix_key3', '111) 

    // Get all keys from memcached. Only returns valid keys 
    $items = $this->memcache->get($keys); 
    // output: array('prefix_key1' => 'value1', 'prefix_key2' => 'value2', 'prefix_key3'=>'value3) 
    // note: key 111 was not found in memcache. 

    // Fill upp eventual keys that are not valid/empty from memcache 
    $return = $items + array_fill_keys($keys, ''); 
    // output: array('prefix_key1' => 'value1', 'prefix_key2' => 'value2', 'prefix_key3'=>'value3, 'prefix_111' => '') 

    // Remove the prefixes for each result before returning array to application 
    foreach ($return as $k => $v) { 
     $expl = explode($prefix, $k); 
     $return[$expl[1]] = $v; 
     unset($return[$k]); 
    } 

    // output: array('key1' => 'value1', 'key2' => 'value2', 'key3'=>'value3, '111' => '') 

    return $return; 

}

고마워요!

편집 : 요청 사이비 코드 : 우리가 KES을 방지하기 위해 모든 키를 접두사 필요 이후

  1. 는, 배열에 접두사를 추가 memcache를
  2. 에서 모든 키를 가져옵니다 memcache에
  3. 에 덮어 쓰기
  4. 유효하지 않은 최종 키를 채우십시오. "유효하지 않은 색인"오류가 발생했습니다. 요청한 키의 사실은가 아닙니다.이 반환되었습니다.
  5. 각 값에 대해 접두어 을 가져올 필요없이 출력 된 키의 서식을 지정하기 위해 접두사를 제거하십시오.
+1

당신은 당신이 원하는 정확히 의사 코드로 설명 할 수 ? – Eric

+0

게시물이 업데이트되었습니다. 감사! – Industrial

답변

2

글쎄, 개인적으로 나는 루프 내에서 배열을 수정하는 것을 좋아하지 않는다. 당신은 그것을 할 수 있지만 내가 (그냥 내 스타일을) 할 것입니다 방법은 다음과 같습니다

function myFunction(array $keys) { 
     $prefixedKeys = array(); 
     $prefix = 'prefix_'; 
     //Since we want the original key later, create a new array of prefixed keys 
     foreach ($keys as $key) { 
      $prefixedKeys[] = $prefix . $key; 
     } 

     $data = $this->memcache->get($prefixedKeys); 

     $return = array(); 
     foreach ($keys as $key) { 
      $prefixedKey = $prefix . $key; 
      //Use the cached key if possible, otherwise default to '' 
      if (isset($data[$prefixedKey])) { 
       $return[$key] = $data[$prefixedKey]; 
      } else { 
       $return[$key] = ''; 
      } 
     } 
     return $return; 
    } 
1

이를 대체 할 수있는이와

for($i=0;$i<$keyCount; $i++){ 
    $keys[] = $prefix.$keys[$i]; 
    unset($keys[$i]); 
} 

을 : 그건 그냥 병합을 실행 취소로

foreach($keys as &$key){ 
    $key = $prefix.$key; 
} 
unset($key); //Necessary because the reference needs to be destroyed 

내가, 당신이 실제로 unset($keys[$i])를 원 생각하지 않습니다.

+0

실제로, unset ($ keys [$ i])는 접두사가 붙지 않는 원래의 키를 제거합니까? – Industrial

+1

예, 키를 끝에 추가하고 시작부터 가져 오니 불안정합니다. 실제 배열 키와 _ 값 키의 일반적인 배열을 혼동하고 있습니다. 'unset ($ array [ 'key'])'배열에서 키의 키를 가진 요소를 제거합니다. – Eric

1

좋아, 전체 솔루션 :

function myFunction ($keys) 
{ 
    $prefix = 'prefix_'; 

    //Create an array to hold 'prefixedkey' => 'key' pairs 
    $prefixedkeys = array(); 
    foreach($keys as $key) 
    { 
     $prefixedkeys[$prefix.$key] = $key; 
    } 

    //Pass memcache just the prefixed keys 
    $items = $this->memcache->get(array_keys($prefixedkeys)); 

    //Create an array to hold the final results 
    $return = array(); 

    foreach($prefixedkeys as $prefixedkey => $key) 
    { 
     if(!isset($items[$prefixedkey])) 
     { 
      //If the memcache data is not set for the current prefixed key, 
      //set the non-prefixed key in $return to '' 
      $return[$key] = ''; 
     } 
     else 
     { 
      //Otherwise, set it to the memcache data for the current prefixed key 
      $return[$key] = $items[$prefixedkey]; 
     } 
    } 
    return $return; 
}