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'); ?>