Home > Article > Backend Development > How to remove key (key name) from two-dimensional array in php
Removal steps: 1. Define an empty array to store the array elements with the key removed, with the syntax "$res=[];"; 2. Use the foreach statement to loop through the outer elements of the two-dimensional array, Syntax "foreach($arr as $v){//loop body code}"; 3. In the loop body, remove the key (key name) of the two-dimensional array, syntax "if(is_array($v)){$res []=array_values($v);}else{$res[]=$v;}".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
In php, you can use foreach statement and the array_values() function to remove the key (key name) of the two-dimensional array.
Implementation steps:
Step 1: Define an empty array to store the array elements with the key (key name) removed
$res=[];
Step 2: Use the foreach statement to loop through the outer array elements of the two-dimensional array
foreach($arr as $v){ //循环体代码 }
Traverse the given $arr array, in each loop Will assign the value of the current array to $v.
Step 3. In the loop body, remove the key (key name) of the outer and inner array elements
Use the is_array() function to determine the outer layer Whether the element is an array type (that is, whether it is the inner array of a two-dimensional array)
If so, use the array_values() function to remove the key (key name) of the inner array , and assign it to the empty array $res
If not, directly assign the key value of the outer element to the empty array $res
if(is_array($v)){ $res[]=array_values($v); }else{ $res[]=$v; }
After the loop ends, the $res array is a two-dimensional array with the key (key name) removed.
Complete implementation code:
<?php header('content-type:text/html;charset=utf-8'); $arr = array( "a"=>1, "b"=>2, "c"=>array("c1"=>3,"c2"=>4,"c3"=>5,"c4"=>6), "d"=>6, "e"=>array("e1"=>7,"e2"=>8,"e3"=>9,"e4"=>10), "f"=>10, "g"=>array("g1"=>11,"g2"=>12,"g3"=>13) ); echo "原二维数组:"; var_dump($arr); $res=[]; foreach($arr as $v){ if(is_array($v)){ $res[]=array_values($v); }else{ $res[]=$v; } } echo "去掉key(键名)的二维数组:"; var_dump($res); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to remove key (key name) from two-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!