成都网站建设设计

将想法与焦点和您一起共享

redis怎么生成树型

这篇文章主要介绍了redis怎么生成树型的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇redis怎么生成树型文章都会有所收获,下面我们一起来看看吧。

创新互联建站专注于高台企业网站建设,成都响应式网站建设公司,商城网站开发。高台网站建设公司,为高台等地区提供建站服务。全流程按需策划设计,专业设计,全程项目跟踪,创新互联建站专业和态度为您提供的服务

一般为了方便管理 redis 缓存,我们通过 : 来分隔不同的 key 来进行存储缓存,这样方便查看。

例如:

game:upload_role:1000
game:member_info:2000
game:member_info:state_info:3000

上面的这种结构在 Redis Desktop Manager 中就会显示如下:

redis怎么生成树型

我们可以通过 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 来显示了。

关于“redis怎么生成树型”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“redis怎么生成树型”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注创新互联行业资讯频道。


名称栏目:redis怎么生成树型
分享路径:http://chengdu.cdxwcx.cn/article/pcipsh.html