##php 模拟hash 拉链法 :)##
<?php
/**
* FILE_NAME:hash.php
* AUTHOR: ChenShuai
* Date: 2017/5/27
* DESC:
*/
class myhash{
public $bucket = [];
/**
* @param $key
* @return int
* @author chenss
* @email css852438363@163.com
* @desc 我用取模的方法 简单模拟加hash
*/
function hash33($key)
{
$hash = 0;
for($i=0; $i<strlen($key); $i++) {
$hash += 33 * $hash + ord($key{$i});
}
return $hash & 0x7FFFFFFF;
}
function setValue($key,$value){
$myhash = $this->hash33($key);
if(isset($this->bucket[$myhash])){
$end = end($this->bucket[$myhash]);
//我这里模拟不了 hash之后 两个数还相等的
$this->bucket[$myhash][$key.'test'] = [
'value'=>$value,
'next'=>array_search($end,$this->bucket[$myhash])
];
}else{
$this->bucket[$myhash][$key] = [
'value'=>$value,
'next'=>null
];
}
}
function getValue($key){
$myhash = $this->hash33($key);
//已经存在 拉链
if(isset($this->bucket[$myhash])){
foreach ($this->bucket[$myhash] as $k => $v){
if($k == $key){
return $v['value'];
}
}
}else{
return '';
}
}
function getAll(){
return $this->bucket;
}
}
$bucket = new myhash();
$bucket->setValue('name','chenshuai');
$bucket->setValue('name','chenshuai2');
$bucket->setValue('age',25);
print_r($bucket->getAll());