search
HomeBackend DevelopmentPHP TutorialPHP implements Redis basic data structure

This article mainly introduces the basic data structure of Redis implemented in PHP, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

Redis basic data structure and PHP implementation


  • Redis (REmote DIctionary Server) is an open source log type written in ANSI C language, complies with the BSD protocol, supports the network, can be based on memory and can be persisted. Key-Value database and provides APIs in multiple languages

  • Redis is often called a data structure server because the value (value) can be a string (String), a hash (Map) ), list (list), collection (Set), and ordered sets (sorted sets) and other types

##Redis configuration and connection

// Redis.php
return [
'host' => '127.0.0.1',
'port' => '6379'
];

// RedisTest.php
$redis = new redis();
$redisConf = include 'Redis.php';
$redis->connect($redisConf['host'], $redisConf['port']);

Redis key (Key)

// redis key操作
$redis->exists($key); // 判断key值是否存在
$redis->expire($key, 10); // 设置key在10秒后过期

Redis String (String)

// redis string 字符串
$redis->set($key, $val);
$redis->incr($key); // key值+1,除非val是整数,否则函数执行失败
$redis->decr($key); // key值-1,同上
$redis->append($key, "ue"); // 追加key值内容
$redis->strlen($key); // 返回key值的长度
// 当第一次设置key值后,key值的数据类型就不能改变了。
$redis->del($key); // 删除key值

Redis Hash(Hash)

  • Redis Hash is a string type Mapping table of field and value, hash is particularly suitable for

    storing objects

  • Each hash in Redis can store 2^(32)-1(more than 40 billion) key-value pairs

//redis hash 哈希
$redis->hset($key, 'field1', 'val1'); // 设置一个key-value键值对
$redis->hmset($key, array('field2'=>'val2', 'field3'=>'val3')); // 设置多个k-v键值对
$redis->hget($key, 'field2'); // 获取hash其中的一个键值
$redis->hmget($key, array('field2', 'field1')); // 获取hash的多个键值
$redis->hgetall($key); // 获取hash中所有的键值对
$redis->hlen($key); // 获取hash中键值对的个数
$redis->hkeys($key); // 获取hash中所有的键
$redis->hvals($key); // 获取hash中所有的值
Redis list(List)

  • Redis list is a simple string list ,

    Sort in order of insertion, you can add the head (left) or tail (right) of an element list

  • A list in Redis can store up to 2^( 32)-1 element

// redis list 列表
$index = $start = 0;
$redis->lpush($key, 'val1', 'val2'); // 在list的开头添加多个值
$redis->lpop($key); // 移除并获取list的第一个元素
$redis->rpop($key); // 移除并获取list的最后一个元素 $stop = $redis->llen($key) - 1; // 获取list的长度
$redis->lindex($key, $index); // 通过索引获取list元素
$redis->lrange($key, $start, $stop); // 获取指定范围内的元素
Redis set (Set)

  • Redis’ Set is of type String. sequence collection. Collection members are unique, which means that

    duplicate data cannot appear in the collection

  • Collections in Redis are implemented through hash tables, so adding and deleting , the search complexity is O(1)

  • A collection in Redis can store up to 2^(32)-1 members

// redis set 无序集合
$redis->sadd($key, 'val1', 'val2'); // 向集合中添加多个元素
$redis->scard($key); // 获取集合元素个数
$redis->spop($key); // 移除并获取集合内随机一个元素
$redis->srem($key, 'val1', 'val2'); // 移除集合的多个元素
$redis->sismember($key, 'val1'); // 判断元素是否存在于集合内
Redis ordered set (sorted set)

  • Redis ordered set, like a set, is also a collection of string type elements, and duplicate members are not allowed

  • The difference is that each element will

    be associated with a double type score . Redis uses scores to sort the members of the set from small to large

  • The members of the ordered set are unique, but the score can be repeated

  • Collections are implemented through hash tables, so the complexity of adding, deleting, and searching is O(1). The maximum number of members in the collection is 2^(32)-1

// redis sorted set 有序集合
// 有序集合里的元素都和一个分数score关联,就靠这个分数score对元素进行排序
$redis->zadd($key, $score1, $val1, $score2, $val2); // 向集合内添加多个元素
$redis->zcard($key); // 获取集合内元素总数
$redis->zcount($key, $minScore, $maxScore); // 获取集合内分类范围内的元素
$redis->zrem($key, $member1, $member2); // 移除集合内多个元素
Redis HyperLogLog

  • Redis HyperLogLog Yes An algorithm used to do cardinality statistics (

    Calculating the number of non-repeating elements in a data set). The advantage of HyperLogLog is that when the number or volume of input elements is very, very large, the space required to calculate the cardinality is always Fixed and very small

  • In Redis, each HyperLogLog key only costs 12 KB of memory to calculate the cardinality of nearly 2^(64) different elements. This is in sharp contrast to a collection where the more elements there are, the more memory is consumed when calculating the cardinality

  • Because HyperLogLog will only calculate the cardinality based on the input elements and will not store the input elements themselves. Therefore, HyperLogLog cannot return each input element like a collection.

$redis->pfAdd('key1', array('elem1', 'elem2'));// 添加指定元素到HyperLogLog中
$redis->pfAdd('key2', array('elem3', 'elem2'));// 将多个HyperLogLog合并为一个HyperLogLog
$redis->pfMerge('key3', array('key1', 'key2'));
$redis->pfCount('key3'); // 返回HyperLogLog的基数估计值: int(3)
The above is the entire content of this article. I hope it will be helpful to everyone's learning. Please pay attention to more related content. PHP Chinese website!


Related recommendations:

The difference between Define and Const in PHP

Interaction between PHP and Web pages

ob_start usage analysis in PHP

The above is the detailed content of PHP implements Redis basic data structure. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment