• 技术文章 >PHP >PHP数组

    php中的哈希表是什么

    小妮浅浅小妮浅浅2021-03-17 10:04:23原创4728

    本文操作系统: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数组

    专题推荐:php哈希表
    品易云
    上一篇:php插值查找的用法 下一篇:哈希表在php中的使用

    相关文章推荐

    • php选择排序是什么意思• php插入排序的使用• php快速排序是什么• php查找算法的理解• php顺序查找的使用• php插值查找的用法

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网