Heim  >  Artikel  >  Backend-Entwicklung  >  PHP删除Array数组里指定的key(完整版,已封装成函数,附测试代码)_PHP教程

PHP删除Array数组里指定的key(完整版,已封装成函数,附测试代码)_PHP教程

WBOY
WBOYOriginal
2016-07-12 09:04:21845Durchsuche

PHP删除Array数组里指定的key(完整版,已封装成函数,附测试代码)

问题背景:array里一般是key---value的存储方式,我们有时候需要删除指定的key及对应的value。但是不知道为啥,那么多帖子都是在讲知道value,并删除该value的事情,差点误导我。

现将我写的完整版代码附下:

 

function array_remove($data, $key){
    if(!array_key_exists($key, $data)){
        return $data;
    }
    $keys = array_keys($data);
    $index = array_search($key, $keys);
    if($index !== FALSE){
        array_splice($data, $index, 1);
    }
    return $data;

}
$data = array('name'=>'apple','age'=>12,'address'=>'ChinaGuangZhou');
$result = array_remove($data, 'name');
var_dump($result);

补充说明:

 

1,其实问题出在array_search这个函数上,这个函数按照value去搜索,得到位置,如果找不到就返回NULL或false;

2,因此,在按key进行查找key对应的位置时,需要在$keys里去找,这就是调用array_keys的原因

3,因为array_search这个函数可能返回NULL和false,所以得按绝对比较,使用!==

 

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1073357.htmlTechArticlePHP删除Array数组里指定的key(完整版,已封装成函数,附测试代码) 问题背景:array里一般是key---value的存储方式,我们有时候需要删除...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn