简体   繁体   English

按DESC顺序排序数组

[英]sort array in DESC order

How can i sort this array by arrray key 我如何通过arrray键对此数组进行排序

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

like this 像这样

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

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);

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. 第二个参数用于保留密钥。

You have an array, you want to sort it by keys, in reverse order -- you can use the krsort function : 你有一个数组,你想按相反的顺序对它进行排序 - 你可以使用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 - 但它似乎不是你想要的,在这里。

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

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

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