php删除特定数组值

首先 var_dump($context[‘linktree’]);

得到
array(3) {
[0]=>
array(2) {
[“url”]=>
string(52) “http://127.0.0.1/testforum.cityofsteam.com/index.php
[“name”]=>
string(28) “City of Steam Official Forum”
}
[1]=>
array(2) {
[“url”]=>
string(55) “http://127.0.0.1/testforum.cityofsteam.com/index.php#c1”
[“name”]=>
string(28) “City of Steam Official Forum”
}
[2]=>
array(2) {
[“url”]=>
string(62) “http://127.0.0.1/testforum.cityofsteam.com/index.php?board=4.0”
[“name”]=>
string(12) “Announcement”
}
}

我要去掉中间那个。

用:unset($context[‘linktree’][‘1’]);

结果:

array(2) {
[0]=>
array(2) {
[“url”]=>
string(52) “http://127.0.0.1/testforum.cityofsteam.com/index.php”
[“name”]=>
string(28) “City of Steam Official Forum”
}
[2]=>
array(2) {
[“url”]=>
string(62) “http://127.0.0.1/testforum.cityofsteam.com/index.php?board=4.0”
[“name”]=>
string(12) “Announcement”
}
}

就少了一个[1]

让这中间的1自动编号:

1
Array ( [0] => apple [1] => banana [3] => dog )
但是这种方法的最大缺点是没有重建数组索引,就是说,数组的第三个元素没了。
经过查资料后,原来PHP提供了这个功能,只不过很间接。这个函数是array_splice()。
为了使用方便,我封装成了一个函数,方便大家使用:
[code]
01
<?php
02

03
function array_remove(&$arr, $offset)
04
{
05
array_splice($arr, $offset, 1);
06
}
07

08
$arr = array(‘apple’,’banana’,’cat’,’dog’);
09

10
array_remove($arr, 2);
11
print_r($arr);
12

13
?>

[/code]
经过测试可以知道,2的位置这个元素被真正的删除了,并且重新建立了索引。
程序运行结果:
1
Array ( [0] => apple [1] => banana [2] => dog )