PHP implements the HASH table Hash table, also known as the HASH table, and maps the Key of the Key to a location in the array to access the record.
The Hash function is used to convert an input of any length into an output of a fixed length using the HASH algorithm. the output is the HASH value.
The time complexity of the HASH table is O (1)
The following uses the direct remainder method for implementation
Create a hashtable
Class HashTable {private $ buckets; // array used to store data private $ size = 12; // record the size of the buckets array public function _ construct () {$ this-> buckets = new SplFixedArray ($ this-> size); // The SplFixedArray is more efficient. you can also use an ordinary array to replace} private function hashfunc ($ key) {$ strlen = strlen ($ key); // returns the string length $ hashval = 0; for ($ I = 0; $ I <$ strlen; $ I ++) {$ hashval + = ord ($ key [$ I]); // returns the ASCII value} return $ hashval % $ this-> size; // return the value after the remainder} 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"
"; Var_dump ($ current); while (isset ($ current) {// traverse the current linked list if ($ current-> key = $ key) {// compare the current node keyword return $ current-> value;} $ current = $ current-> nextNode; // return $ current-> value;} return NULL ;}}
The above may cause conflicts, such as the HASH table pointing
Insert two elements. the HASH value of the second element is the same as the HASH value of the first element.
The second element overwrites the value of the first element.
In this case, we use the zipper method to solve the conflict: links with the same HASH value byte points are in the same linked list. When searching for this element, you must traverse this linked list.
Create a HASHNODE
Class HashNode {public $ key; // keyword public $ value; // data public $ nextNode; // HASHNODE to store information public function _ construct ($ key, $ value, $ nextNode = NULL) {$ this-> key = $ key; $ this-> value = $ value; $ this-> nextNode = $ nextNode ;}}
Implementation
$ht = new HashTable(); $ht->insert('key1','value1'); //$ht->insert('key12','value12');echo $ht->find('key1');