【发布时间】:2011-02-22 22:14:03
【问题描述】:
我有点头疼。该函数可以满足我的要求,但是由于我还不太熟悉 PHP:s 数组/循环函数,因此我的问题是,从性能角度来看,该函数是否有任何部分可以改进?
$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 在内存缓存中被覆盖
- 从内存缓存中获取所有键
- 填写无效的最终密钥, 因为我们想避免任何 “not-valid-index”错误由 请求密钥的事实不是 返回。
- 删除前缀以格式化输出的键 更容易而无需获得前缀 每个值。
【问题讨论】:
-
你能用伪代码解释一下你想要做什么吗?
标签: php arrays foreach for-loop