简体   繁体   English

如何删除缓存中的密钥? (laravel 5.3)

[英]How can I remove a key in cache? (laravel 5.3)

If I run: 如果我运行:

echo '<pre>';print_r(Cache('test'));echo '</pre>';die();

the result is like this : 结果是这样的:

Array
(
    [0] => Array
        (
            [id] => 42
            [name] => real madrid
            [description] => ronaldo
        )

    [1] => Array
        (
            [id] => 41
            [name] => chelsea
            [description] => hazard
        )

)

I want to remove the key that has the id = 42. 我要删除id = 42的密钥。

I try like this : 我这样尝试:

$id = 42;
foreach (Cache('test') as $key => $value) {
      if($key['id'] == $id) {
           Cache::forget($key);
      }
}

Then, I run: 然后,我运行:

dd(Cache('test'));

But the key with id = 42 is still there. 但是id = 42的密钥仍然存在。

The entry in cache is called test , and it is an array with multiple elements; 缓存中的条目称为test ,它是一个包含多个元素的数组; so trying to delete an entry from cache with the id value 42 won't work because entry 42 isn't the cache entry, just a part of the array. 因此尝试从缓存中删除ID值为42条目将不起作用,因为条目42不是缓存条目,而只是数组的一部分。

$ttl = 240;

$id = 42;
// retrieve the array from Cache
$value = Cache::get('test');
// Identify the entry with id of 42
$entry = array_flip(array_column($value, 'id'));
// delete that entry from the array
unset($value[$entry[$id]]);
// restore the modified array to cache
Cache::put('test', $value, $ttl)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM