asort

asort(array &$array, int $flags = SORT_REGULAR): true

按值升序就地排序数组,全程保持键值关联。

C C23

C23
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    const char *name;
    int age;
} Pair;

static int by_age(const void *a, const void *b) {
    return ((const Pair *)a)->age - ((const Pair *)b)->age;
}

int main(void) {
    Pair ps[] = {{"carol", 31}, {"alice", 24}, {"bob", 19}};
    size_t n = sizeof ps / sizeof ps[0];
    qsort(ps, n, sizeof ps[0], by_age); // C 无关联数组:对结构体数组排序
    for (size_t i = 0; i < n; i++) {
        printf("%s=%d\n", ps[i].name, ps[i].age);
    }
    return 0;
}
输出
bob=19
alice=24
carol=31

C++ C++26

C++26
#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
int main() {
    std::vector<std::pair<std::string, int>> ages{{"carol", 31}, {"alice", 24}, {"bob", 19}};
    std::sort(ages.begin(), ages.end(),
              [](const auto &a, const auto &b) { return a.second < b.second; });
    for (const auto &[name, age] : ages) std::cout << name << "=" << age << "\n";
    return 0;
}
输出
bob=19
alice=24
carol=31

C# v11.0.100

v11.0.100
using System;
using System.Collections.Generic;
using System.Linq;

var ages = new Dictionary<string, int> { ["carol"] = 31, ["alice"] = 24, ["bob"] = 19 };
foreach (var kv in ages.OrderBy(kv => kv.Value)) // LINQ 返回新的有序序列
{
    Console.WriteLine($"{kv.Key}={kv.Value}");
}
输出
bob=19
alice=24
carol=31

Go v1.27.4

v1.27.4
package main

import (
    "fmt"
    "sort"
)

func main() {
    ages := map[string]int{"carol": 31, "alice": 24, "bob": 19}
    names := make([]string, 0, len(ages))
    for name := range ages {
        names = append(names, name)
    }
    sort.Slice(names, func(i, j int) bool { // map 无序:按值给键排序
        return ages[names[i]] < ages[names[j]]
    })
    for _, name := range names {
        fmt.Printf("%s=%d\n", name, ages[name])
    }
}
输出
bob=19
alice=24
carol=31

Java v27.0.1

v27.0.1
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> ages = new HashMap<>();
        ages.put("carol", 31);
        ages.put("alice", 24);
        ages.put("bob", 19);
        var entries = new ArrayList<>(ages.entrySet());
        entries.sort(Map.Entry.comparingByValue());
        Map<String, Integer> sorted = new LinkedHashMap<>(); // 按排序结果重建
        for (var e : entries) sorted.put(e.getKey(), e.getValue());
        System.out.println(sorted);
    }
}
输出
{bob=19, alice=24, carol=31}

JavaScript v26.13.1

v26.13.1
const ages = { carol: 31, alice: 24, bob: 19 };
// 对象按插入序保留键:用按值排序后的键值对重建
const sorted = Object.fromEntries(Object.entries(ages).sort((a, b) => a[1] - b[1]));
console.log(sorted);
输出
{ bob: 19, alice: 24, carol: 31 }

PHP v8.6.0

v8.6.0
$ages = ["carol" => 31, "alice" => 24, "bob" => 19];
asort($ages); // 按值排序,键值关联保持不变
foreach ($ages as $name => $age) {
    echo $name, "=", $age, "\n";
}
输出
bob=19
alice=24
carol=31

Python v3.15.2

v3.15.2
ages = {"carol": 31, "alice": 24, "bob": 19}
# 字典按插入序保留键:用按值排序后的条目重建
print(dict(sorted(ages.items(), key=lambda kv: kv[1])))
输出
{'bob': 19, 'alice': 24, 'carol': 31}

Rust v1.99.1

v1.99.1
fn main() {
    let mut ages = vec![("carol", 31), ("alice", 24), ("bob", 19)];
    ages.sort_by_key(|&(_, age)| age); // 键值对整体参与排序
    for (name, age) in &ages {
        println!("{}={}", name, age);
    }
}
输出
bob=19
alice=24
carol=31

TypeScript v26.13.1

v26.13.1
const ages: Record<string, number> = { carol: 31, alice: 24, bob: 19 };
const sorted = Object.fromEntries(Object.entries(ages).sort((a, b) => a[1] - b[1]));
console.log(sorted);
输出
{ bob: 19, alice: 24, carol: 31 }

语言差异说明

C:没有关联数组,结构体数组 + qsort 是等价惯用法。

C#:Dictionary 无序,LINQ OrderBy 返回惰性新序列最顺手(Sort() 只存在于 List<T>)。

Go:map 本身无序,惯用「收集键 → 按值排序 → 遍历取值」。

Java:HashMap 无序,收集 entry 排序后写入 LinkedHashMap。

JavaScript:对象字符串键按插入序,Object.fromEntries(sortedEntries) 重建。

PHP:asort 按值升序且全程保持键→值关联——这是它与 sort(排序后重建数字索引)的本质区别,也是「带键排序」族的核心行为;同族:arsort(按值降序)、ksort(按键)、uasort(自定义回调且保键)。

Python:3.7+ dict 记住插入序,dict(sorted(d.items(), key=...)) 重建即等效。

Rust:BTreeMap 按键自动有序但「按值」排序只能用元组 Vec + sort_by_key。