PHP修改和组合数组

标签 php arrays foreach for-loop

我有点头疼数组。该函数可以满足我的要求,但由于我还不太熟悉 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;

非常感谢!

编辑:请求的伪代码:

  1. 给数组添加前缀,因为我们 需要为每个键添加前缀以防止 kes在内存缓存中被覆盖
  2. 从memcache中获取所有key
  3. 填写无效的最终 key , 因为我们想避免任何 由以下原因引起的“无效索引”错误 请求 key 的事实不是 返回。
  4. 删除前缀以格式化输出的键 无需前缀更容易 对于每个值。

最佳答案

嗯,我个人不喜欢在循环中修改数组(取消设置等)。你可以做到,但我会怎么做(只是我的风格):

    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/

相关文章:

php - mysql wildcard (%) 在不使用通配符时给出不同的结果

php - 如何将项目添加到 magento 面包屑

c - 使用带有数组的函数?代码不起作用

javascript - 如何在完成具有 axios 调用的 for/forEach 循环执行后调用语句?

php - 使用 PHP 两个 MySQL 时间变量之间的减法

php - 删除 mySQL 中引用的行

php - 将 php 代码转换为 Objective-C

javascript - 返回对象的一个​​元素并创建该元素的新数组

arrays - 数组上的 Angular 循环在解析 csv 后创建对象数组

javascript - 像javascript中的对象一样在数组上应用forEach方法