为什么array_unique对值进行排序? [英] Why does array_unique sort the values?

查看:195
本文介绍了为什么array_unique对值进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我以前的问题之一: array_unique与array_flip -此状态 array_flip(array_flip()) array_unique() 处理简单的字符串和整数时.

This refers to one of my previous questions: array_unique vs array_flip - This states that array_flip(array_flip()) is much quicker than array_unique() when dealing with simple strings and integers.

我想知道的是为什么 array_unique() 创建数组的副本,然后对其进行排序删除重复项

What I would like to know is why array_unique() creates a copy of the array, sorts it then removed the duplicates

这两个函数的来源均可用

The source for both functions is available here.

提前谢谢!

推荐答案

如果从算法上考虑,删除重复项的方法是遍历一个列表,跟踪找到的项目,并清除那些已经在找到此"列表中.一种简单的方法是对列表进行排序.这样,很明显在哪里可以有效地删除重复项.想想你,更不用说电脑了;这些列表中的哪一个更容易从中删除重复项?

If you think about it algorithmically, the way to remove duplicates is to go through a list, keep track of items you find, and get rid of things that are already in that "found this" list. One easy way to accomplish this is to sort a list. That way it's obvious where to remove duplicates efficiently. Think about you, let alone a computer; which one of these lists is easier to remove duplicates from?

apple
banana
cantaloupe
apple
durian
apple
banana
cantaloupe

apple
apple
apple
banana
banana
cantaloupe
cantaloupe
durian

:仔细研究了一下(并找到

After looking into it a bit (and finding this article), it looks like while the two both get the job done, they are not functionally equivalent, or at least they aren't always. To paraphrase a couple of these points:

    如您所述,
  1. array_unique()对值进行排序,因此array_flip(array_flip())不会返回相同顺序的数组,但这可能是需要的.
  2. 如果值是对象,则不能将它们设置为键(对吗?),即,对于所有数组,flip方法都无法开箱即用,而无论哪种方法,sort方法都可以正常工作值类型.
  1. array_unique() sorts the values, as you noted, so array_flip(array_flip()) wouldn't return the same-ordered array -- but this might be desired.
  2. If the values are objects, then you can't make them keys (right?), i.e. the flip method wouldn't work out of the box on all arrays, whereas the sort method works fine, regardless of the value types.

这篇关于为什么array_unique对值进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆