ZetCode

PHP usort 函数

最后修改于 2025 年 3 月 13 日

PHP usort 函数使用用户定义的比较函数对数组进行排序。它允许使用标准排序函数无法实现的自定义排序逻辑。

基本定义

usort 函数使用您提供的比较函数按值对数组进行排序。它为数组元素保留索引关联。

语法:usort(array &$array, callable $callback): bool。回调函数定义了排序顺序。它直接修改原始数组。

如果第一个参数被认为分别小于、等于或大于第二个参数,则回调函数必须分别返回小于、等于或大于零的整数。

基本数字排序

本示例演示了降序自定义数字排序。

basic_usort.php
<?php

declare(strict_types=1);

$numbers = [3, 1, 4, 1, 5, 9, 2, 6];

usort($numbers, function($a, $b) {
    return $b <=> $a; // Reverse spaceship operator for descending
});

print_r($numbers);

回调函数使用反向的宇宙飞船运算符 (<=>) 来以降序对数字进行排序。数组原地修改。

排序关联数组

使用 usort 按特定键对关联数组进行排序。

associative_sort.php
<?php

declare(strict_types=1);

$users = [
    ['name' => 'Alice', 'age' => 28],
    ['name' => 'Bob', 'age' => 22],
    ['name' => 'Charlie', 'age' => 25]
];

usort($users, function($a, $b) {
    return $a['age'] <=> $b['age'];
});

print_r($users);

这会按升序按年龄对用户进行排序。回调函数比较每个关联数组元素中的“age”值。

按属性对对象排序

使用 usort 根据属性值对对象数组进行排序。

object_sort.php
<?php

declare(strict_types=1);

class Product {
    public function __construct(
        public string $name,
        public float $price
    ) {}
}

$products = [
    new Product("Laptop", 999.99),
    new Product("Phone", 699.99),
    new Product("Tablet", 399.99)
];

usort($products, function($a, $b) {
    return $a->price <=> $b->price;
});

foreach ($products as $product) {
    echo "{$product->name}: {$product->price}\n";
}

产品按升序按价格排序。回调函数访问对象属性以确定排序顺序。

多条件排序

使用 usort 实现具有多个条件的复杂排序。

multi_criteria.php
<?php

declare(strict_types=1);

$employees = [
    ['name' => 'Alice', 'department' => 'Sales', 'salary' => 5000],
    ['name' => 'Bob', 'department' => 'IT', 'salary' => 6000],
    ['name' => 'Charlie', 'department' => 'Sales', 'salary' => 5500],
    ['name' => 'David', 'department' => 'IT', 'salary' => 5500]
];

usort($employees, function($a, $b) {
    // First by department (ascending)
    $deptCompare = $a['department'] <=> $b['department'];
    if ($deptCompare !== 0) {
        return $deptCompare;
    }
    // Then by salary (descending)
    return $b['salary'] <=> $a['salary'];
});

print_r($employees);

员工首先按部门字母顺序排序,然后在每个部门内按工资降序排序。回调函数实现了此逻辑。

不区分大小写的字符串排序

使用自定义比较函数不区分大小写地排序字符串。

case_insensitive.php
<?php

declare(strict_types=1);

$names = ["apple", "Banana", "cherry", "Date"];

usort($names, function($a, $b) {
    return strcasecmp($a, $b);
});

print_r($names);

strcasecmp 函数执行不区分大小写的字符串比较。这可确保“Banana”出现在“apple”和“cherry”之间。

最佳实践

来源

PHP usort 文档

本教程介绍了 PHP usort 函数,并通过实际示例展示了其在自定义数组排序场景中的用法。

作者

我的名字是 Jan Bodnar,我是一名热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直在撰写编程文章。至今,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出 所有 PHP 数组函数