In PHP, we can use a variety of methods to query elements in an array, such as using the in_array() function, using the array_search() function, etc. But when we need to query elements in a two-dimensional array, these methods are less effective. This article will introduce how to query a two-dimensional array in PHP and return the required elements.
First, let us look at a simple two-dimensional array:
$students = array( array('name' => 'Tom', 'age' => 20, 'score' => 90), array('name' => 'Jack', 'age' => 22, 'score' => 85), array('name' => 'Mary', 'age' => 21, 'score' => 92), );
Suppose we want to query the grades of a certain student, we can use foreach to loop through the array and use conditional statements to Determine whether they are the students we need, for example:
$wantedStudent = 'Jack'; foreach ($students as $student) { if ($student['name'] == $wantedStudent) { echo $wantedStudent . '的成绩是:' . $student['score']; break; } }
The above code will output:
Jack的成绩是:85
However, if we need to query many students, this method will become very cumbersome. Therefore, we can encapsulate it into a function for use:
function searchArray($array, $key, $value) { foreach ($array as $item) { if ($item[$key] == $value) { return $item; } } return null; }
The above function receives three parameters: array, key name and key value to be queried. It will iterate through the array and if it finds a match, it returns that item, otherwise it returns null.
We can use the function like this:
$wantedStudent = 'Mary'; $student = searchArray($students, 'name', $wantedStudent); if ($student) { echo $wantedStudent . '的成绩是:' . $student['score']; }
The above code is equivalent to the previous example and will output:
Mary的成绩是:92
However, when the array is very large, Iterating over the entire array will impact performance. Therefore, we can use the array function array_filter(), which takes an array and a callback function and returns a new array containing the array elements that meet the callback function's conditions.
The following is an example of using array_filter() to query a two-dimensional array:
function searchArray($array, $key, $value) { $filtered = array_filter($array, function($item) use ($key, $value) { return $item[$key] == $value; }); return count($filtered) ? array_values($filtered)[0] : null; }
The function of the above function is the same as the previous function, but it uses array_filter() to filter the conditions. array elements, thereby improving performance.
So far, we have learned how to query a two-dimensional array in PHP and return the required elements. It is recommended to use array_filter() and anonymous functions to implement array element query when there are hundreds or more pieces of data.
The above is the detailed content of PHP query returns a two-dimensional array. For more information, please follow other related articles on the PHP Chinese website!