哈希表是計算機科學中極其重要的數據結構,能以接近 O(1) 的時間複雜度完成插入、查找與刪除。本文提供一個基於 SplFixedArray 的完整 PHP 哈希表實現,涵蓋雜湊算法、碰撞處理、動態擴容等核心機制。
class hashTable {
private $collection;
private $size = 100;
public function __construct($size = '') {
$bucketsSize = is_int($size) ? $size : $this->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];
}
public function del($key) {
$index = $this->_hashAlgorithm($key);
if (isset($this->collection[$index])) {
unset($this->collection[$index]);
return 1;
}
return 0;
}
public function exist($key) {
$index = $this->_hashAlgorithm($key);
return $this->collection[$index] ? 1 : 0;
}
public function size() {
$count = 0;
foreach ($this->collection as $val) {
if ($val) $count++;
}
return $count;
}
public function val() {
foreach ($this->collection as $val) {
if ($val) echo $val . "
";
}
}
public function sort($type = 1) { /* ... 省略排序實現 ... */ }
public function rev($type = 1) { /* ... 省略逆序實現 ... */ }
}
$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);
foreach 遍歷。理解並手寫哈希表,有助於深入掌握 PHP 底層數組的實現原理。