Hash表作为最重要的数据结构之一,也叫做散列表。使用PHP实现Hash表的功能。PHP可以模拟实现Hash表的增删改查。通过对key的映射到数组中的一个位置来访问。映射函数叫做Hash函数,存放记录的数组称为Hash表。

Hash函数把任意长度的和类型的key转换成固定长度输出。不同的key可能拥有相同的hash。
Hash表的时间复杂度为O(1)

class HashTable{
private $arr = array();
private $size=10;
public function __construct(){
$this->arr = new SplFixedArray($this->size);
}
public function SimpleHash($key){
$len = strlen($key);
$ascTotal=0;
for($i=0;$i<$len;$i++){
$ascTotal+=ord($key[$i]);
}
return $ascTotal%$this->size;
}
//添加
public function set($key,$value){
$hash = $this->SimpleHash($key);
$this->arr[$hash]=$value;
return true;
}
//获取
public function get($key){
$hash = $this->SimpleHash($key);
return $this->arr[$hash];
}
//获取列表
public function getList(){
print_r($this->arr);
}
//修改hash大小
public function editSize($size){
$this->size = $size;
$this->arr->setSize($size);
}
}
$objtable = new HashTable();
$objtable->set("test",40);
$objtable->set('a',10);
$objtable->editSize(40);