php 按 DESC 顺序对数组进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2045401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:47:26  来源:igfitidea点击:

sort array in DESC order

phparrayssorting

提问by antpaw

How can i sort this array by arrray key

我如何通过数组键对这个数组进行排序

array(
4 => 'four',
3 => 'three',
2 => 'two',
1 => 'one',
)

like this

像这样

array(
1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four',
)

回答by Alix Axel

If you want to sort the keys in DESC order use:

如果要按 DESC 顺序对键进行排序,请使用:

krsort($arr);

If you want to sort the values in DESC order and maintain index association use:

如果要按 DESC 顺序对值进行排序并维护索引关联,请使用:

arsort($arr);

If you want to sort the values in DESC natural order and maintain index association use:

如果要按 DESC 自然顺序对值进行排序并维护索引关联,请使用:

natcasesort($arr);
$arr = array_reverse($arr, true);

回答by Gumbo

If you just want to reverse the order, use array_reverse:

如果您只想颠倒顺序,请使用array_reverse

$reverse = array_reverse($array, true);

The second parameter is for preserving the keys.

第二个参数用于保留密钥。

回答by Pascal MARTIN

You have an array, you want to sort it by keys, in reverse order -- you can use the krsortfunction :

您有一个数组,您想按相反的顺序按键对其进行排序 - 您可以使用该krsort函数:

Sorts an array by key in reverse order, maintaining key to data correlations. This is useful mainly for associative arrays.

以相反的顺序按键对数组进行排序,保持数据相关性的键。这主要用于关联数组。


In you case, you'd have this kind of code :


在你的情况下,你会有这样的代码:

$arr = array(
    1 => 'one',
    2 => 'two',
    3 => 'three',
    4 => 'four',
);

krsort($arr);
var_dump($arr);

which would get you this kind of output :

这会让你得到这种输出:

$ /usr/local/php-5.3/bin/php temp.php
array(4) {
  [4]=>
  string(4) "four"
  [3]=>
  string(5) "three"
  [2]=>
  string(3) "two"
  [1]=>
  string(3) "one"
}


As a sidenode : if you had wanted to sort by values, you could have used arsort-- but it doesn't seem to be what you want, here.


作为一个sidenode:如果你想按值排序,你可以使用arsort- 但它似乎不是你想要的,在这里。

回答by Paul Dixon

Try krsort()- that will sort in reverse using the array key, whereas rsort will sort on the array value.

尝试krsort()- 这将使用数组键进行反向排序,而 rsort 将根据数组值进行排序。