Home >Backend Development >PHP Problem >How to query multiple specified data in an array in php

How to query multiple specified data in an array in php

PHPz
PHPzOriginal
2023-04-20 13:50:37571browse

In PHP programming, it is often necessary to query specific multiple pieces of data in an array. This kind of query is usually implemented using for loops and if statements. The following will introduce how to query multiple pieces of data in an array in PHP.

First, we need a sample array, the data is as follows:

<?php
$users = array(
    array(&#39;id&#39; => 1, 'name' => '张三', 'age' => 18),
    array('id' => 2, 'name' => '李四', 'age' => 25),
    array('id' => 3, 'name' => '王五', 'age' => 31),
    array('id' => 4, 'name' => '赵六', 'age' => 20),
    array('id' => 5, 'name' => '钱七', 'age' => 27),
);
?>

This array contains 5 user information, each user has three fields: id, name, and age.

Next, we will implement query for user information whose age is greater than or equal to 25 years old. The code is as follows:

<?php
$result = array();
for ($i=0; $i<count($users); $i++) {
    if ($users[$i][&#39;age&#39;] >= 25) {
        $result[] = $users[$i];
    }
}
print_r($result);
?>

In this code, we use a for loop to traverse the entire array and check each user The age field is greater than or equal to 25 years old. If so, add the user information to the $result array. Finally, by outputting the data in the $result array, you can get information about all users whose age is greater than or equal to 25 years old.

In the same way, we can also query multiple pieces of data with other conditions. For example, to query user information whose name contains "Zhang", the code is as follows:

<?php
$result = array();
for ($i=0; $i<count($users); $i++) {
    if (strpos($users[$i][&#39;name&#39;], &#39;张&#39;) !== false) {
        $result[] = $users[$i];
    }
}
print_r($result);
?>

In this code, we use the PHP built-in function strpos to determine whether the name contains "Zhang". If so, the user will be The information is added to the $result array.

To sum up, querying specific multiple pieces of data in an array can be achieved through for loops and if statements. According to different query conditions, we can write corresponding if statements and add qualified data to the result array. Although this method is relatively simple, the performance may not be very good for large arrays or complex queries. It is recommended to use a more suitable method such as a database to handle it.

The above is the detailed content of How to query multiple specified data in an 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