品易云推流 关闭
文章详情页
文章 > PHP数组 > php中的哈希表是什么

php中的哈希表是什么

php哈希表

头像

小妮浅浅

2021-03-17 10:04:235706浏览 · 0收藏 · 0评论

本文操作系统:windows7系统、PHP5.6版本、DELL G3电脑

1.概念

哈希表是一种通过哈希函数,将特定的键映射到特定值的一种数据结构,它维护键和值之间一一对应关系。

2.说明

(1)哈希表是一种数据结构

(2)哈希表表示了关键码值和记录的映射关系

(3)哈希表可以加快查找速度

(4)任意哈希表,都满足有哈希函数f(key),代入任意key值都可以获取包含该key值的记录在表中的地址

3.实例

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

以上就是php中哈希表的基本内容介绍,相信大家已经初步认识了这种操作数组的方法。在有了基础的概念理解后,在接下来的学习中就可以不断就哈希表进行应用了。更多php学习指路:php数组

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图