php array_flip() 删除数组重复元素_PHP教程

WBOY
Release: 2016-07-21 15:47:57
Original
1100 people have browsed it

方法如下:
$arr = array(…………) ;//假设有一万个元素的数组,里面有重复的元素。
$arr = array_flip(array_flip($arr)); //这样便可以删除重复元素。

究竟是怎么回事呢?来看下array_flip()的作用:array_flip()用于将一个数组的每个元素的键和值交换,如:
$arr1 = array (”age” => 30, “name” => “快乐园”);
$arr2 = array_flip($arr1); //$arr2 就是 array(30 => “age”, “快乐园” => “name”);
在PHP的数组中,允许不同的元素可以取同一个值,但不允许同一个键名被不同的元素使用,如:
$arr1 = array (”age” => 30, “name” => “快乐园”, “age” => 20); “age” => 20将会取代”age” => 30
$arr1 = array (”name” => “快乐园”, “age” => 45);
这里 $arr1与$arr2 是相等的。
于是,我们便可以知道,为什么 array_flip(array_flip($arr)) 可以删除数组中重复的元素了。首先,$arr里的值会变成键名,因为值是有重复的,变成键名之后这些重复的值便成了重复的键名,PHP引擎将重复的键名删除,只保留最后一个。如:
$arr1 = array (”age” => 30, “name” => “快乐园”, “age” => 20);
$arr1 = array_flip($arr1); //$arr1 变成了 array(”快乐园” => “name”, 20 => “age”);
//再把 $arr1 的键名与值还复:
$arr1 = array_flip($arr1);

上面的代码写得简洁一些就是: $arr1 = array_flip(array_flip($arr1));

www.bkjia.com true http://www.bkjia.com/PHPjc/319822.html TechArticle 方法如下: $arr = array(…………) ;//假设有一万个元素的数组,里面有重复的元素。 $arr = array_flip(array_flip($arr)); //这样便可以删除重复元素。...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!