Home > Article > Backend Development > How to remove the key of a two-dimensional array in PHP
In PHP development, we often use arrays to store some data, and each element in the array consists of a key and a value. In some cases, we need to remove the keys from the array and retain only the values in the array. This requires the use of some functions provided in PHP to remove array keys.
So, how to remove the key of a two-dimensional array? Here are some commonly used methods.
1. Use the array_values() function
The array_values() function will return an array containing only element values, not the keys and values in the original array. This function converts a two-dimensional array into a one-dimensional array, retaining all values.
For example:
$array = array( array('id'=>1,'name'=>'张三'), array('id'=>2,'name'=>'李四') ); $array = array_map('array_values',$array); print_r($array);
The output result is:
Array ( [0] => Array ( [0] => 1 [1] => 张三 ) [1] => Array ( [0] => 2 [1] => 李四 ) )
2. Use foreach loop
Another way to remove the key of a two-dimensional array is to use foreach Loop through each element and store the value of each element into a new array. During this process, we can use the unset() function to delete the key and keep only the value.
For example:
$array = array( array('id'=>1,'name'=>'张三'), array('id'=>2,'name'=>'李四') ); $newArray = array(); foreach($array as $item){ $newArray[] = array_values($item); } print_r($newArray);
The output result is:
Array ( [0] => Array ( [0] => 1 [1] => 张三 ) [1] => Array ( [0] => 2 [1] => 李四 ) )
3. Use the array_map() function
array_map() function to convert the incoming array into Each element is passed to the callback function for processing, and a new array is returned. The elements of the array are the results of applying the callback function to each element. We can use the array_values() function in the callback function to remove the keys of the array.
For example:
$array = array( array('id'=>1,'name'=>'张三'), array('id'=>2,'name'=>'李四') ); $newArray = array_map(function($item){ return array_values($item); }, $array); print_r($newArray);
The output result is:
Array ( [0] => Array ( [0] => 1 [1] => 张三 ) [1] => Array ( [0] => 2 [1] => 李四 ) )
Summary
The above are three methods to remove keys from two-dimensional arrays in PHP. In actual development, we can choose the most suitable method according to the specific situation. Whichever method you use, you should take care to preserve the values of the array and keep your code as concise and readable as possible.
The above is the detailed content of How to remove the key of a two-dimensional array in PHP. For more information, please follow other related articles on the PHP Chinese website!