【发布时间】:2014-08-23 08:35:04
【问题描述】:
根据 PHP 文档,array_unique 删除重复值并首先对作为字符串处理的值进行排序。
当您记住以下 sn-p 时:
// define a simple array of strings, unordered
$brands = [ "BMW", "Audi", "BMW", "Chrysler", "Daewoo"];
// distinct the values, and sort them
echo array_unique($brands, SORT_STRING);
我希望输出是:
expected: {"0":"Audi","1":"BMW","3":"Chrysler","4":"Daewoo"}
actual : {"0":"BMW","1":"Audi","3":"Chrysler","4":"Daewoo"}
问题是:为什么 array_unique 不对这些值进行排序?将 sort_flags 参数更改为四个选项中的任何一个,或者将其留空,也没有任何效果。
根据其他 SO 问题,例如"Why does array unique sort the values",我可能在这里遗漏了一些明显的东西。此外,使用array_values(array_unique($brands)),如this question 中的答案所述,似乎也不起作用。
更新:正如有用的 cmets 和答案中所述,sort_flags 参数实际上是一种内部比较行为,或者说相等运算符。
【问题讨论】:
-
array_unique不会对数组元素进行排序。它只是从数组中删除重复值。该手册仅提及有关内部(临时)数组处理的 sorts 词。这并不意味着真正的数组排序 -
那么,实际上'sort_flag'真的应该被解释为'compare_behaviour'吗?如果是这样,命名约定和前面提到的帖子让我在这部分感到困惑。
标签: php arrays sorting array-unique