PHP redis 使用BitMap存储setbit批量写入与getbit批量查询方法
程序员文章站
2022-07-05 20:37:38
...
普通单条用法不详细说明文档都有,下面主要介绍批量的写入与查询。
php7.1写法
/**
* 批量向 setBit中添加元素
*
* @param string $key setBit 的key
* @param array $elems 待添加元素的集合,每一项为array('key' => value)
* @param string $size 大小 u1代表无符号1位
* @return int
*/
public function setBitArray(string $key, array $elems, string $size = 'u1'): int
{
if (!$key || !is_array($elems)){
return false;
}
$p = [];
foreach ($elems as $k => $v){
$p[] = 'set';
$p[] = $size;
$p[] = $k;
$p[] = $v;
}
$result = $this->_redis->rawCommand('bitField',$key, ...$p);
return $result;
}
/**
* 批量查询 getBit 元素值
*
* @param string $key
* @param array $data 查询元素的数组集合,每一项为array('key','key1','key2'.....'keyN')
* @param string $size
* @return array array('key'=>val,'key1'=>val,...)
*/
public function getBitArray(string $key, array $data, string $size = 'u1') :array
{
if (!$key || !is_array($data)){
return false;
}
$p = [];
foreach ($data as $k => $v){
$p[] = 'get';
$p[] = $size;
$p[] = $v;
}
$result1 = $this->_redis->rawCommand('bitField',$key, ...$p);
$result =[];
foreach ($data as $k => $v){
$result[$v] = $result1[$k];
}
return $result;
}
7.1以下的写法逻辑没啥区别
/**
* 批量向 setBit中添加元素
*
* @param string $key setBit 的key
* @param array $elems 待添加元素的集合,每一项为array('key' => value)
* @param string $size 大小 u1代表无符号1位
* @return int
*/
public function setBitArray($key, $elems, $size = 'u1')
{
if (!$key || !is_array($elems)){
return false;
}
$p = [];
foreach ($elems as $k => $v){
$p[] = 'set';
$p[] = $size;
$p[] = $k;
$p[] = $v;
}
$result = $this->_redis->rawCommand('bitField',$key, ...$p);
return $result;
}
/**
* 批量查询 getBit 元素值
*
* @param string $key
* @param array $data 查询元素的数组集合,每一项为array('key','key1','key2'.....'keyN')
* @param string $size
* @return array array('key'=>val,'key1'=>val,...)
*/
public function getBitArray($key, $data, $size = 'u1')
{
if (!$key || !is_array($data)){
return false;
}
$p = [];
foreach ($data as $k => $v){
$p[] = 'get';
$p[] = $size;
$p[] = $v;
}
$result1 = $this->_redis->rawCommand('bitField',$key, ...$p);
$result =[];
foreach ($data as $k => $v){
$result[$v] = $result1[$k];
}
return $result;
}