search
HomeBackend DevelopmentPHP ProblemHow to perform fuzzy query on array in php

In PHP development, arrays are an inevitable part of us. When we need to query data in an array, we usually use fuzzy queries. This article will introduce how to perform fuzzy query of arrays in PHP.

1. What is array fuzzy query

Array fuzzy query, that is, data query based on keywords, does not require a complete match, only matching items are required to return results. In actual development, array fuzzy queries are often used to find data with similar characteristics.

For example, we have a contact group that contains multiple contact information, including name, phone number, email address and other information. We can use fuzzy queries to find a person's contact information, or even enter only part of a name or phone number to find results.

2. Use array_filter() for fuzzy query

PHP’s array_filter() function can conditionally filter each element in the array and return results that meet the conditions. We can use this function to implement fuzzy query of arrays.

Suppose we have a users array that contains multiple contact information:

$users = array(
    array('name' => '张三', 'phone' => '13811112222', 'email' => 'zhangsan@example.com'),
    array('name' => '李四', 'phone' => '13911113333', 'email' => 'lisi@example.com'),
    array('name' => '王五', 'phone' => '15011112222', 'email' => 'wangwu@example.com'),
    array('name' => '赵六', 'phone' => '18011114444', 'email' => 'zhaoliu@example.com')
);

Now, we want to implement the function of finding users based on keywords. We can define a function, pass in keywords and user arrays, and use the array_filter() function to filter elements in the array that meet the conditions.

function search_users($keyword, $users) {
    $result = array_filter($users, function($user) use ($keyword) {
        foreach($user as $value) {
            if(stripos($value, $keyword) !== false) {
                return true;
            }
        }
        return false;
    });
    return $result;
}

The above function will perform a loop comparison of each user information and return true when a match is found. The stripos() function can retrieve the first occurrence of a string in another string, case-insensitively.

We can call this function to perform fuzzy query:

$search_result = search_users('1111', $users);

This query will return all contact information whose phone number contains "1111".

Using the array_filter() function to implement fuzzy queries on arrays is simple and easy to use, but it also has a problem: when the amount of data in the array is large, performance may be affected. At this time, we can use another way to implement fuzzy query of the array.

3. Use regular expressions for fuzzy query

Regular expression is a tool used to match and replace text. In PHP, we can use the preg_grep() function to filter out elements that meet conditions in an array based on regular expressions.

Suppose we have a keywords array that contains multiple keywords:

$keywords = array('1111', 'san', 'y@example');

Now, we want to find all contact information that meets the keyword conditions in the users array. We can use regular expressions to achieve this function:

function search_users_regex($keywords, $users) {
    $result = array();
    foreach ($keywords as $keyword) {
        $pattern = '/' . preg_quote($keyword, '/') . '/i'; // i表示不区分大小写
        // preg_grep()返回满足条件的元素的数组
        $matches = preg_grep($pattern, $users);
        $result = array_merge($result, $matches);
    }
    return $result;
}

The above function will loop through the keywords array, generate a regular expression for each keyword, use preg_grep() to match, and contact the qualified Person information is merged into a result array.

We can call this function to perform fuzzy query:

$search_result = search_users_regex($keywords, $users);

This query will return all contact information that meets any keyword condition, including phone numbers containing "1111" and names containing "san", the email address contains the contact information of "y@example".

Using regular expressions to perform fuzzy queries on arrays can more accurately find results that meet the conditions, but it also has a disadvantage: the construction of regular expressions requires certain knowledge and skills. If it is not written well, the code will May become difficult to understand and maintain.

4. Summary

Array fuzzy query is one of the commonly used functions in PHP development, which can help us quickly find elements in the array that meet conditions. This article introduces two ways to implement array fuzzy query, namely using the array_filter() function and using regular expressions. In actual development, we can choose a suitable method for implementation based on actual needs. At the same time, we should also pay attention to the impact that fuzzy queries may have on performance and optimize query efficiency as much as possible.

The above is the detailed content of How to perform fuzzy query on array in php. 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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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