⼀般为了⽅便管理 redis 缓存,我们通过 : 来分隔不同的 key 来进⾏存储缓存,这样⽅便查看。例如:
game:upload_role:1000game:member_info:2000
game:member_info:state_info:3000
上⾯的这种结构在 Redis Desktop Manager 中就会显⽰如下:
我们可以通过 keys 命令来获取 redis ⾥的所有 key。但这些 key 是没有层次的,如何⽣成?只能通过 : 分隔符来处理各 key 的上下层关系。代码如下:
function relationCache($keys, &$index, &$index_tree){
$result = []; if ($keys) {
foreach ($keys as $key) { $arr = explode(':', $key); $len = count($arr);
for ($ix = 0; $ix < $len; $ix++) {
$cur_key = implode(':', array_slice($arr, 0, $ix + 1)); if (!isset($index_tree[$cur_key])) { $index_tree[$cur_key] = $index++;
$pid = 0; if ($ix >= 1) {
$pre_key = implode(':', array_slice($arr, 0, $ix)); $pid = $index_tree[$pre_key]; }
$result[] = [
'id' => $index_tree[$cur_key], 'pid' => $pid,
'name' => $arr[$ix], 'key' => $cur_key, ]; } } } }
return $result;}
然后⽣成树型的函数如下:
function genTree($items, $id = 'id', $pid = 'pid', $son = 'child'){
$tree = array(); $tmpMap = array();
foreach ($items as $item) {
$tmpMap[$item[$id]] = $item; }
foreach ($items as $item) {
if (isset($tmpMap[$item[$pid]])) {
$tmpMap[$item[$pid]][$son][] = &$tmpMap[$item[$id]]; } else {
$tree[] = &$tmpMap[$item[$id]]; } }
unset($tmpMap);
return $tree;}
使⽤如下:
$keys = [
'game:upload_role:1000', 'game:member_info:2000',
'game:member_info:state_info:3000',];
//索引
$index = 1;//索引树
$index_tree = [];
//注意,如果想多次调⽤relationCache,并共享索引,请通过外部传参的⽅式$result = relationCache($keys, $index, $index_tree);$result = genTree($result, 'id', 'pid', 'children');echo '
';print_r($result);这样⽣成的结果,通过json_encode就可以使⽤ zTree 来显⽰了。
因篇幅问题不能全部显示,请点此查看更多更全内容