场景: 需在 PHP 内存中,多字段排序,类比 MySQL 中的 order by column1 desc, column2 asc

题目: 数据表中存在学生表,有年纪、分数两个字段,从数据库取出数据后,请在 PHP 内存中按年纪倒叙,分数正序排列

解答: 用 array_multisort 实现

$arrayFetchFromMysql = [
    [
        'id' => 1,
        'age' => 16,
        'score' => 86,
    ],
    [
        'id' => 2,
        'age' => 18,
        'score' => 95,
    ],
    [
        'id' => 3,
        'age' => 25,
        'score' => 60,
    ]
];

array_multisort(
    array_column($arrayFetchFromMysql, 'age'), SORT_DESC, 
    array_column($arrayFetchFromMysql, 'score'), SORT_ASC, 
    $arrayFetchFromMysql
);

exit(json_encode($arrayFetchFromMysql));

打印结果

[
    {
        "id": 3,
        "age": 25,
        "score": 60
    },
    {
        "id": 2,
        "age": 18,
        "score": 95
    },
    {
        "id": 1,
        "age": 16,
        "score": 86
    }
]

解析

php.net 对 array_multisort 定义 https://www.php.net/manual/zh/function.array-multisort.php

该操作需配合 array_coumn 函数,以上题目是两个字段排序,对更多字段排序也可以复用以上套路。