asort() 函數同樣對陣列值進行升序排序,但會保留鍵值關聯,這是它與 sort() 最大的不同。適用於需維持鍵名意義的關聯陣列。
asort(array &$array, int $flags = SORT_REGULAR): bool
$nums = array("one"=>5, "two"=>2, "three"=>1);
asort($nums);
foreach ($nums as $key => $val) {
echo "$key = $val<br />";
}
three = 1 two = 2 one = 5
| 函數 | 排序依據 | 鍵名保留 |
|---|---|---|
| sort() | 值 | 否(重置為 0,1,2...) |
| asort() | 值 | 是 |
SORT_NUMERIC:數值排序SORT_STRING:字串排序SORT_NATURAL:自然排序若需降序排序,請使用 arsort()。