//一個簡單的哈希表實現。。。。
size;
$this->collection = new SplFixedArray($bucketsSize);
}
//生成散列值,作為存儲數據的位置
private function _hashAlgorithm($key)
{
$length = strlen($key);
$hashValue = 0;
for($i=0; $i<$length; $i++) {
$hashValue += ord($key[$i]);
}
return ($hashValue%($this->size));
}
//在相應的位置存儲對應的值
public function set($key, $val)
{
$index = $this->_hashAlgorithm($key);
$this->collection[$index] = $val;
}
//根據鍵生成散列值,進而找到對應的值
public function get($key)
{
$index = $this->_hashAlgorithm($key);
return $this->collection[$index];
}
//刪除某個值,成功返回1,失敗返回0
public function del($key)
{
$index = $this->_hashAlgorithm($key);
if(isset($this->collection[$index])) {
unset($this->collection[$index]);
return 1;
} else {
return 0;
}
}
//判斷某個值是否存在,存在返回1, 不存在返回0
public function exist($key)
{
$index = $this->_hashAlgorithm($key);
if($this->collection[$index]){
return 1;
} else {
return 0;
}
}
//返回key的個數
public function size()
{
$size = 0;
$length = count($this->collection);
for($i=0; $i<$length; $i++) {
if($this->collection[$i]) {
$size++;
}
}
return $size;
}
//返回value的序列
public function val()
{
$size = 0;
$length = count($this->collection);
for($i=0; $i<$length; $i++) {
if($this->collection[$i]) {
echo $this->collection[$i]."
";
}
}
}
//排序輸出
public function sort($type=1)
{
$length = count($this->collection);
$temp = array();
for($i=0; $i<$length; $i++) {
if($this->collection[$i]) {
$temp[] = $this->collection[$i];
}
}
switch ($type) {
case 1:
//正常比較
sort($temp, SORT_REGULAR);
break;
case 2:
//按照數字比較
sort($temp, SORT_NUMERIC);
break;
//按照字符串進行比較
case 3:
sort($temp, SORT_STRING);
break;
//根據本地字符編碼環境進行比較
case 4:
sort($temp, SORT_LOCALE_STRING);
break;
}
echo "";
print_r($temp);
}
//逆序輸出
public function rev($type=1)
{
$length = count($this->collection);
$temp = array();
for($i=0; $i<$length; $i++) {
if($this->collection[$i]) {
$temp[] = $this->collection[$i];
}
}
switch ($type) {
case 1:
//正常比較
rsort($temp, SORT_REGULAR);
break;
case 2:
//按照數字比較
rsort($temp, SORT_NUMERIC);
break;
//按照字符串進行比較
case 3:
rsort($temp, SORT_STRING);
break;
//根據本地字符編碼環境進行比較
case 4:
rsort($temp, SORT_LOCALE_STRING);
break;
}
echo "";
print_r($temp);
}
}
//簡單的測試
$list = new hashTable(200);
$list->set("zero", "zero compare");
$list->set("one", "first test");
$list->set("two", "second test");
$list->set("three", "three test");
$list->set("four", "fouth test");
echo $list->val();
echo "after sorted :
";
$list->rev(3);