php的數組實際上就是hash_table,無論是 數字索引數組array(1, 2, 3) 還是關聯數組array(1 => 2, 2=> 4)等等。
PHP中哈希表結構
假定向PHP數組中插入三個元素分別為Bucket1,Bucket2,Bucket3,其中Bucket1和Bucket2的key具有相同的哈希值。其在哈希表中存儲如圖所示:

從上圖可知,(1)哈希表中同一個哈希值對應元素存儲在雙向鏈表中。(2)PHP數組<key,value>,將key代入哈希函數,很快獲得哈希值。然后遍歷此哈希值對應鏈表,獲取鏈表中某個屬性是key的節點,此節點的值是value。PHP數組中獲取key的速率高於value,可以利用此優勢。
代碼實現
<?php class HashTable { private $buckets; //用於存儲數據的數組 private $size = 12; //記錄buckets 數組的大小 public function __construct() { $this->buckets = new SplFixedArray($this->size); //SplFixedArray效率更高,也可以用一般的數組來代替 } private function hashfunc($key) { $strlen = strlen($key); //返回字符串的長度 $hashval = 0; for ($i = 0; $i < $strlen; $i++) { $hashval += ord($key[$i]); //返回ASCII的值 } return $hashval % 12; // 返回取余數后的值 } public function insert($key, $value) { $index = $this->hashfunc($key); if (isset($this->buckets[$index])) { $newNode = new HashNode($key, $value, $this->buckets[$index]); } else { $newNode = new HashNode($key, $value, null); } $this->buckets[$index] = $newNode; } public function find($key) { $index = $this->hashfunc($key); $current = $this->buckets[$index]; echo "</br>"; var_dump($current); while (isset($current)) { //遍歷當前鏈表 if ($current->key == $key) { //比較當前結點關鍵字 return $current->value; } $current = $current->nextNode; //return $current->value; } return null; } } class HashNode { public $key; //關鍵字 public $value; //數據 public $nextNode; //HASHNODE來存儲信息 public function __construct($key, $value, $nextNode = null) { $this->key = $key; $this->value = $value; $this->nextNode = $nextNode; } } $ht = new HashTable(); $ht->insert('Bucket1', 'value1'); $ht->insert('Bucket2', 'value2'); $ht->insert('Bucket3', 'value3'); echo $ht->find('Bucket1'); ?>
