根据 PHP 文档,array_unique删除重复值并首先将值排序为字符串。
当您记住以下代码段时:
// 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 问题,例如“为什么数组对值进行唯一排序”,我可能在这里遗漏了一些明显的东西。此外,使用array_values(array_unique($brands))
, 作为这个问题的答案似乎也不起作用。
更新:正如有用的评论和答案中所述,sort_flags参数实际上是一种内部比较行为,或者说相等运算符。