简体   繁体   English

php array_unique 排序行为

[英]php array_unique sorting behavior

I am checking the array_unique function.我正在检查 array_unique 函数。 The manual says that it will also sort the values.手册说它也会对值进行排序。 But I cannot see that it is sorting the values.但我看不到它正在对值进行排序。 Please see my sample code.请参阅我的示例代码。

$input = array("a" => "green", 3=>"red", "b" => "green", 1=>"blue", "red");
print_r($input);
$result = array_unique($input,SORT_STRING);
print_r($result);

The output is

Array
(
    [a] => green
    [3] => red
    [b] => green
    [1] => blue
    [4] => red
)
Array
(
    [a] => green
    [3] => red
    [1] => blue
)

Here the array $result is not sorted.这里数组 $result 没有排序。 Any help is appreciated.任何帮助表示赞赏。

Thank you Pramod谢谢普拉莫德

array_unique:数组唯一:

Takes an input array and returns a new array without duplicate values.接受一个输入数组并返回一个没有重复值的新数组。

Note that keys are preserved.请注意,密钥被保留。 array_unique() keeps the first key encountered for every value, and ignore all following keys. array_unique() 保留每个值遇到的第一个键,并忽略所有后续键。

you can try this to get the result:你可以试试这个来得到结果:

<?php 
$input = array("a" => "green", 3=>"red", "b" => "green", 1=>"blue", "red");
print_r($input);
$result = array_unique($input);
print_r($result);
asort($result);
print_r($result);

The manual does not say it will sort the array elements, it says that the sort_flags parameters modifies the sorting behavior.手册没有说它会对数组元素进行排序,它说sort_flags参数修改了排序行为。

The optional second parameter sort_flags may be used to modify the sorting behavior using these values: [...]可选的第二个参数 sort_flags 可用于使用以下值修改排序行为:[...]

The sorting behavior is used to sort the array values in order to perform the comparison and determine whether one element is considered to be equal to another.排序行为用于对数组值进行排序,以执行比较并确定一个元素是否与另一个元素相等。 It does not modify the order of the underlying array.它不会修改底层数组的顺序。

If you want to sort your array, you'll have to do that as a separate operation.如果要对数组进行排序,则必须将其作为单独的操作进行。 Documentation on array sorting can be found here .可以在此处找到有关数组排序的文档。

For a default ascending sort based on the array's values, you could use asort .对于基于数组值的默认升序排序,您可以使用asort

array_unique takes an input array and returns a new array without duplicate values. array_unique接受一个输入数组并返回一个没有重复值的新数组。 It doesn't sort actually.它实际上没有排序。 Read more at http://php.net/manual/en/function.array-unique.phphttp://php.net/manual/en/function.array-unique.php阅读更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM