Home Backend Development PHP Problem How to perform fuzzy query on array in php

How to perform fuzzy query on array in php

Apr 26, 2023 am 10:28 AM

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')
);
Copy after login

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;
}
Copy after login

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);
Copy after login

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');
Copy after login

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;
}
Copy after login

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);
Copy after login

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 of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

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 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 Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

What is the purpose of mysqli_query() and mysqli_fetch_assoc()? What is the purpose of mysqli_query() and mysqli_fetch_assoc()? Mar 20, 2025 pm 04:55 PM

The article discusses the mysqli_query() and mysqli_fetch_assoc() functions in PHP for MySQL database interactions. It explains their roles, differences, and provides a practical example of their use. The main argument focuses on the benefits of usin

How do you retrieve data from a database using PHP? How do you retrieve data from a database using PHP? Mar 20, 2025 pm 04:57 PM

Article discusses retrieving data from databases using PHP, covering steps, security measures, optimization techniques, and common errors with solutions.Character count: 159

PHP CSRF Protection: How to prevent CSRF attacks. PHP CSRF Protection: How to prevent CSRF attacks. Mar 25, 2025 pm 03:05 PM

The article discusses strategies to prevent CSRF attacks in PHP, including using CSRF tokens, Same-Site cookies, and proper session management.

See all articles