array_unique() - 移除数组中重复的值 - php 数组函数
array_unique()
(PHP 4 >= 4.0.1, PHP 5, PHP 7)
移除数组中重复的值
说明
array_unique(array $array[,int $sort_flags= SORT_STRING]): arrayarray_unique()接受$array作为输入并返回没有重复值的新数组。
注意键名保留不变。array_unique()先将值作为字符串排序,然后对每个值只保留第一个遇到的键名,接着忽略所有后面的键名。这并不意味着在未排序的$array中同一个值的第一个出现的键名会被保留。
Note:当且仅当(string)$elem1 ===(string)$elem2时两个单元被认为相同。例如,字符串表达一样时,会使用首个元素。
参数
$array输入的数组。
$sort_flags第二个可选参数$sort_flags可用于修改排序行为:
排序类型标记:
SORT_REGULAR
-按照通常方法比较(不修改类型)SORT_NUMERIC
-按照数字形式比较SORT_STRING
-按照字符串形式比较SORT_LOCALE_STRING
-根据当前的本地化设置,按照字符串比较。
返回值
返回过滤后的数组。
更新日志
版本 | 说明 |
---|---|
5.2.10 | 修改回$sort_flags的默认值为SORT_STRING 。 |
5.2.9 | 增加可选选项$sort_flags,默认值SORT_REGULAR 。 5.2.9 之前,此函数内部使用SORT_STRING 排序。 |
范例
Example #1array_unique()例子
以上例程会输出:
Array ( [a] => green [0] => red [1] => blue )
Example #2array_unique()和类型
以上例程会输出:
array(2) { [0] => int(4) [2] => string(1) "3" }
参见
- array_count_values() 统计数组中所有的值
注释
Note:注意,array_unique()不能应用于多维数组。
Create multidimensional array unique for any single key index. e.g I want to create multi dimentional unique array for specific code Code : My array is like this, You can make it unique for any field like id, name or num. I have develop this function for same : Now, call this function anywhere from your code, something like this, Output will be like this :
It's often faster to use a foreache and array_keys than array_unique:
In reply to performance tests array_unique vs foreach. In PHP7 there were significant changes to Packed and Immutable arrays resulting in the performance difference to drop considerably. Here is the same test on php7.1 here; http://sandbox.onlinephpfunctions.com/code/2a9e986690ef8505490489581c1c0e70f20d26d1 $max = 770000; //large enough number within memory allocation $arr = range(1,$max,3); $arr2 = range(1,$max,2); $arr = array_merge($arr,$arr2); $time = -microtime(true); $res1 = array_unique($arr); $time += microtime(true); echo "deduped to ".count($res1)." in ".$time; // deduped to 513333 in 1.0876770019531 $time = -microtime(true); $res2 = array(); foreach($arr as $key=>$val) { $res2[$val] = true; } $res2 = array_keys($res2); $time += microtime(true); echo "
deduped to ".count($res2)." in ".$time; // deduped to 513333 in 0.054931879043579
For people looking at the flip flip method for getting unique values in a simple array. This is the absolute fastest method: It's marginally faster as: And it's marginally slower as: It's still about twice as fast or fast as array_unique. This tested on several different machines with 100000 random arrays. All machines used a version of PHP5.
I needed to identify email addresses in a data table that were replicated, so I wrote the array_not_unique() function:
recursive array unique for multiarrays
Case insensitive; will keep first encountered value.
I created a function for doing array_unique with a custom in_array function. So, if elements are considered in the array passed to this function, the array returned won't include elements that are considered equal and only return the values from the first array that are not considered in the array: Example usage:
Taking the advantage of array_unique, here is a simple function to check if an array has duplicate values. It simply compares the number of elements between the original array and the array_uniqued array.
If you find the need to get a sorted array without it preserving the keys, use this code which has worked for me: The above code returns an array which is both unique and sorted from zero.
This is a script for multi_dimensional arrays
The following is an efficient, adaptable implementation of array_unique which always retains the first key having a given value: It is also adaptable to multi dimensional arrays. For example, if your array is a sequence of (multidimensional) points, then in place of @$aHash[$val]++ you could use @$aHash[implode("X",$val)]++ If you want to not have holes in your array, you can do an array_merge($aray) at the end. Csaba Gabor
another method to get unique values is : Output: Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f )
I found the simplest way to "unique" multidimensional arrays as follows: As you can see "b" will be removed without any errors or notices.
My object unique function: And these code: returns: object(Test)[1] public 'pr0' => string 'string' (length=6) public 'pr1' => string 'string1' (length=7) public 'pr3' => string 'string2' (length=7)
so .... my problem was multidimensional sort. Array $attribs is an array contaning arrays. Each array in the $attrib array consists in multiple fields (ex: name, lenght, price, etc.) to be more simpler in speech think that $attrib is the array resulted by a search sql query done by a visitator on your online shoopping website ... (so ... each array in the $attrib is a product :P) if you want to sort only the uniq results use the above or use this: Have fun tweaking this ;)) i know you will ;)) From Romania With Love
Although array_unique is not intended to work with multi-dimensional arrays, it does on 5.2.9. However, it does not for 5.2.5. Beware.
[Editor's note: please note that this will not work well with non-scalar values in the array. Array keys can not be arrays themselves, nor streams, resources, etc. Flipping the array causes a change in key-name] You can do a super fast version of array_unique directly in PHP, even faster than the other solution posted in the comments! Compared to the built in function it is 20x faster! (2x faster than the solution in the comments). This works faster for small and big arrays.
Another form to make an array unique (manual): This is my array Array ( [0] => Array ( [0] => 40665 [1] => 40665 [2] => 40665 [3] => 40665 [4] => 40666 [5] => 40666 [6] => 40666 [7] => 40666 [8] => 40667 [9] => 40667 [10] => 40667 [11] => 40667 [12] => 40667 [13] => 40668 [14] => 40668 [15] => 40668 [16] => 40668 [17] => 40668 [18] => 40669 [19] => 40669 [20] => 40670 [21] => 40670 [22] => 40670 [23] => 40670 [24] => 40671 [25] => 40671 [26] => 40671 [27] => 40671 [28] => 40671 ) [1] => Array ( [0] => 40672 [1] => 40672 [2] => 40672 [3] => 40672 ) ) this is my script: $anterior = 0; foreach($item as $array_key => $array_value) { echo "
- ";
foreach($array_value as $xarray_key => $xarray_value){
if($xarray_value != $anterior) {
echo "
- $xarray_key => $xarray_value"; $item_nuevo[$array_key][] = $xarray_value; // or to use the same key number $item_nuevo[$array_key][$xarray_key] = $xarray_value; } $anterior = $xarray_value; } echo "
I searched how to show only the de-duplicate elements from array, but failed. Here is my solution: Example: Output: Array ( [4] => xyzzy [12] => | [16] => & [21] => foobar )
Another way to 'unique column' an array, in this case an array of objects: Keep the desired unique column values in a static array inside the callback function for array_filter. Example: In addition, use array_merge( $unique ) to reindex.
I find it odd that there is no version of this function which allows you to use a comparator callable in order to determine items equality (like array_udiff and array_uintersect). So, here's my version for you: And here is a test code:
Simple and clean way to get duplicate entries removed from a multidimensional array.
As for PHP 7.1.12, this is the comparison between array_keys(array_flip()), array_flip(array_flip()), for each elimination and array_unique. The array_keys(array_flip()) is the fastest method to remove duplication values from a single dimension array:
In case you are looking for a function that works like array_unique but does not do the string conversion first.
Lets say that you want to capture unique values from multidimensional arrays and flatten them in 0 depth. i.e. will return with array_flat( $tmp ) --> array( 1,2,3,4,5,6,7 ); I hope that the function will help someone
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!
内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)