Home > Article > Backend Development > How to query data in a two-dimensional array in php
Two-dimensional array in PHP is an effective method to save multiple data. It consists of multiple arrays, each array contains multiple elements. In this case, querying the location of data in a two-dimensional array is a common task. This article will introduce how to use functions in PHP to query data in a two-dimensional array.
I. Create a simple two-dimensional array
First, let us create a simple two-dimensional array that contains multiple arrays.
$students = array( array('name'=>'Tom', 'age'=>20, 'grade'=>'A'), array('name'=>'Mary', 'age'=>19, 'grade'=>'B'), array('name'=>'John', 'age'=>22, 'grade'=>'C'), array('name'=>'Jane', 'age'=>21, 'grade'=>'A'), array('name'=>'Jack', 'age'=>18, 'grade'=>'B') );
In this array, each array represents a student's information, including name, age and grades. Different student information is stored in different arrays.
II. Finding data in a two-dimensional array
Next, let’s see how to use functions to find data in a two-dimensional array.
This function can get a certain column in the input array and return them as an array. In this example, we will use this function to get the name of the student whose age is 20 years old.
$result = array_column($students, 'name', 'age'); echo $result[20];
Note that we use the third parameter in the array_column() function to specify the key name of the returned array, so that we can access the key-value pairs more easily. The output is: Tom.
If we need to find the position of a specific element in an array, we can use the array_search() function.
$search = 'John'; foreach($students as $key => $value){ if(in_array($search, $value)){ echo "The key is " . $key; break; } }
In this example, we iterate through the entire array and then use the in_array() function to find a specific value in the current array. If the corresponding value is found, we will output the key name of the array in the two-dimensional array. The output result is: The key is 2.
III. Conclusion
In PHP, we can use some built-in functions to find specific elements in a two-dimensional array. The array_column() function can easily obtain the data of a specific column, while the array_search() function can find the position of a specific element in the array. These functions can greatly simplify the process of program development, especially when processing large amounts of data. Using these functions can improve the efficiency of the program.
The above is the detailed content of How to query data in a two-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!