PHP如何删除基于键的数组元素
来源:藏色散人
发布时间:2019-03-23 15:11:29
阅读量:1522
给定一个数组(一维或多维),任务是根据键值删除一个数组元素。

例子如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 输入: Array
(
[0] => 'G'
[1] => 'E'
[2] => 'E'
[3] => 'K'
[4] => 'S'
)
Key = 2
输出: Array
(
[0] => 'G'
[1] => 'E'
[3] => 'K'
[4] => 'S'
)
|
使用unset()函数: unset()函数用于从数组中删除元素。unset函数用于销毁任何其他变量,同样用于删除数组的任何元素。此unset命令将数组键作为输入,并从数组中删除该元素。删除后,关联的键和值不会更改。
语法:
参数:该函数接受单个参数变量。它是必需参数,用于取消设置元素。
程序1:从一维数组中删除元素。
1 2 3 4 5 6 7 | <?php
$arr = array ( 'G' , 'E' , 'E' , 'K' , 'S' );
print_r( $arr );
unset( $arr [2]);
print_r( $arr );
?>
|
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Array
(
[0] => G
[1] => E
[2] => E
[3] => K
[4] => S
)
Array
(
[0] => G
[1] => E
[3] => K
[4] => S
)
|
程序2:从关联数组中删除元素。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?php
$marks = array (
"Ankit" => array (
"C" => 95,
"DCO" => 85,
),
"Ram" => array (
"C" => 78,
"DCO" => 98,
),
"Anoop" => array (
"C" => 88,
"DCO" => 46,
),
);
echo "删除元素前 <br>" ;
print_r( $marks );
unset( $marks [ "Ram" ]);
echo "删除元素后 <br>" ;
print_r( $marks );
?>
|
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | 删除元素前
Array
(
[Ankit] => Array
(
[C] => 95
[DCO] => 85
)
[Ram] => Array
(
[C] => 78
[DCO] => 98
)
[Anoop] => Array
(
[C] => 88
[DCO] => 46
)
)
删除元素后
Array
(
[Ankit] => Array
(
[C] => 95
[DCO] => 85
)
[Anoop] => Array
(
[C] => 88
[DCO] => 46
)
)
|