下面是一个典型的k-v存储格式的PHP实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
class db { public function test() { //..... } private function pack($arr) { $str = ''; foreach($arr as $key=>$val) { $str .= pack("n", strlen($key)).pack("n", strlen($val)).$key.$val; } return $str; } private function unpackUserInfo($str) { $arrResult = array(); $len = strlen($str); if ($len < 5) return $arrResult; $pos = 0; while($len - $pos >= 5) { $arr1 = unpack("n", substr($str, $pos, 2)); $arr2 = unpack("n", substr($str, $pos+2, 2)); $len_key = $arr1[1]; $len_val = $arr2[1]; $key = substr($str, $pos + 4, $len_key); $val = substr($str, $pos + 4 + $len_key, $len_val); $pos += 4 + $len_key + $len_val; $arrResult[$key] = $val; } return $arrResult; } } |
注意:
1. pack(“n”,…) 使得key、value长度都限制在65535以内