我有点头疼数组。该函数可以满足我的要求,但由于我还不太熟悉 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在内存缓存中被覆盖
- 从memcache中获取所有key
- 填写无效的最终 key , 因为我们想避免任何 由以下原因引起的“无效索引”错误 请求 key 的事实不是 返回。
- 删除前缀以格式化输出的键 无需前缀更容易 对于每个值。
最佳答案
嗯,我个人不喜欢在循环中修改数组(取消设置等)。你可以做到,但我会怎么做(只是我的风格):
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;
}
关于PHP修改和组合数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2891850/