arsort
(PHP 4, PHP 5, PHP 7, PHP 8)
arsort — 对数组进行降向排序并保持索引关系
说明
对 array
本身按照降序排序,并保持数组的键与值之间的关联。
主要用于对那些单元顺序很重要的结合数组进行排序。
注意:
如果两个成员完全相同,那么它们将保持原来的顺序。 在 PHP 8.0.0 之前,它们在排序数组中的相对顺序是未定义的。
注意:
重置数组中的内部指针,指向第一个元素。
参数
array
-
输入的数组。
flags
-
可选的第二个参数
flags
可以用以下值改变排序的行为:排序类型标记:
-
SORT_REGULAR
- 正常比较单元 详细描述参见 比较运算符 章节 -
SORT_NUMERIC
- 单元被作为数字来比较 -
SORT_STRING
- 单元被作为字符串来比较 -
SORT_LOCALE_STRING
- 根据当前的区域(locale)设置来把单元当作字符串比较,可以用 setlocale() 来改变。 -
SORT_NATURAL
- 和 natsort() 类似对每个单元以“自然的顺序”对字符串进行排序。 -
SORT_FLAG_CASE
- 能够与SORT_STRING
或SORT_NATURAL
合并(OR 位运算),不区分大小写排序字符串。
-
返回值
总是返回 true
。
示例
示例 #1 arsort() 示例
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
arsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
以上示例会输出:
a = orange d = lemon b = banana c = apple
fruits 被按照字母顺序逆向排序,并且单元的索引关系不变。
+添加备注
用户贡献的备注 3 notes
morgan at anomalyinc dot com ¶
25 years ago
If you need to sort a multi-demension array, for example, an array such as
$TeamInfo[$TeamID]["WinRecord"]
$TeamInfo[$TeamID]["LossRecord"]
$TeamInfo[$TeamID]["TieRecord"]
$TeamInfo[$TeamID]["GoalDiff"]
$TeamInfo[$TeamID]["TeamPoints"]
and you have say, 100 teams here, and want to sort by "TeamPoints":
first, create your multi-dimensional array. Now, create another, single dimension array populated with the scores from the first array, and with indexes of corresponding team_id... ie
$foo[25] = 14
$foo[47] = 42
or whatever.
Now, asort or arsort the second array.
Since the array is now sorted by score or wins/losses or whatever you put in it, the indices are all hoopajooped.
If you just walk through the array, grabbing the index of each entry, (look at the asort example. that for loop does just that) then the index you get will point right back to one of the values of the multi-dimensional array.
Not sure if that's clear, but mail me if it isn't...
-mo
stephenakins at gmail dot com ¶
7 years ago
I have two servers; one running 5.6 and another that is running 7. Using this function on the two servers gets me different results when all of the values are the same.
<?php
$list = json_decode('{"706":2,"703":2,"702":2,"696":2,"658":2}', true);
print_r($list);
arsort($list);
echo "<br>";
print_r($list);
?>
PHP 5.6 results:
Array ( [706] => 2 [703] => 2 [702] => 2 [696] => 2 [658] => 2 )
Array ( [658] => 2 [696] => 2 [702] => 2 [703] => 2 [706] => 2 )
PHP 7 results:
Array ( [706] => 2 [703] => 2 [702] => 2 [696] => 2 [658] => 2 )
Array ( [706] => 2 [703] => 2 [702] => 2 [696] => 2 [658] => 2 )