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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

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.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor