首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 實現哈希表:從原理到完整類庫

     編輯:PHP 相關知識

PHP 實現哈希表:從原理到完整類庫

哈希表是計算機科學中極其重要的數據結構,能以接近 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 底層數組的實現原理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved