### **可以用作用戶資料等場景,一個大類下有許多子類,如用戶資料下有姓名,性別,年齡等,各個子類都有對應的值**
* 與 PHP 的 Array 相似
* 可以保存多個 key-value 對,每個k-v 都是字符串類型
* 最多 2 的 32 次方 -1 個字段
### **1.常見的操作**
1. 賦值
`$redis->hSet('key','filed','value');`
2. 賦值多個字段
`$redis->hMset('key',array('filed1' => 'value1','filed2' => 'value2'));`
3. 取值
`$redis->hGet('key','filed');`
4. 取多個字段的值
`$redis->hmGet('key',array('filed1','field2'));`
5. 取所有字段的值
`$redis->hGetAll('key');`
6. 獲取字段的數量
`$redis->hLen('key');`
7. 判斷字段是否存在
`$redis->hExists('key',field);`
8. 當字段不存在時賦值
`$redis->hSetNx('key',field,value);`
9. 增加數字
`$redis->hIncrBy('key',field,num);`
10. 刪除字段
`$redis->hDel('key');`
11. 獲取所有字段名
`$redis->hKeys('key');`
12. 獲取所有字段值
`$redis->hVal('key');`
### **2.封裝自己的 redis hash**
#### 1.編寫類
```
/**
* hash賦值
*/
public static function hset($key, $field, $value)
{
return self::getWrite()->hSet($key, $field, $value);
// 如 用戶資料-姓名-張三
}
/**hash取值
* @param $key
* @param string $field
* @return array|false|string
*/
public static function hget($key, $field = '')
{
if (empty($field)) {
return self::getRead()->hGetAll($key);
} else {
return self::getRead()->hGet($key, $field);
}
}
/**自增
* @param $key
* @param $field
* @param int $number
* @return mixed
*/
public static function hincrby($key, $field, $number = 1)
{
return self::getWrite()->hIncrBy($key,$field,$number);
}
```