Home > Article > Backend Development > How to get the key name of a two-dimensional array in php
In PHP development, two-dimensional arrays are often used. A two-dimensional array is a main array in which each element is split into a sub-array. Each sub-array can have multiple elements, and each element has a key and a value. Usually, we need to obtain the key name of the two-dimensional array (that is, the element name in the main array) so that we can be more convenient and flexible when processing data. Below, we will introduce several ways for PHP to obtain the key names of two-dimensional arrays.
1. Use array_keys() function
array_keys() function can return all unique key names in the main array. If the array is multi-dimensional, only the key names of the first dimension will be returned. . Therefore, when we need to get the key name of the first dimension, we can use the array_keys() function.
Sample code:
$array = array( 'a' => array('name' => '小明', 'age' => 18), 'b' => array('name' => '小红', 'age' => 20), 'c' => array('name' => '小李', 'age' => 22) ); $keys = array_keys($array); print_r($keys);
Output result:
Array ( [0] => a [1] => b [2] => c )
2. Using foreach loop
We can use the foreach loop statement to traverse the main array, and then loop through The $key variable in the body gets the key name of each element. It should be noted that when we deal with multi-dimensional arrays, the internal loops also need to be nested to traverse each sub-array and obtain its corresponding key name.
Sample code:
$array = array( 'a' => array('name' => '小明', 'age' => 18), 'b' => array('name' => '小红', 'age' => 20), 'c' => array('name' => '小李', 'age' => 22) ); foreach($array as $key => $value){ echo $key."\n"; foreach($value as $i => $j){ echo $i."\n"; } }
Output result:
a name age b name age c name age
3. Use array_map() function
array_map() function can apply customized functions to each element in one or more arrays and returns a new array. We can customize a function to get the key name of each element in the main array.
Sample code:
$array = array( 'a' => array('name' => '小明', 'age' => 18), 'b' => array('name' => '小红', 'age' => 20), 'c' => array('name' => '小李', 'age' => 22) ); function get_key($value){ return array_keys($value)[0]; } $keys = array_map('get_key', $array); print_r($keys);
Output result:
Array ( [0] => a [1] => b [2] => c )
Summary
In PHP, we can use the array_keys() function, foreach loop and array_map( ) function to get the key name of the two-dimensional array. The appropriate method should be selected based on specific development needs. At the same time, we also need to further understand the nature and characteristics of PHP arrays, and learn to use different array functions to implement different operations.
The above is the detailed content of How to get the key name of a two-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!