ZetCode

PHP 数组排序

最后修改于 2025 年 3 月 13 日

PHP 提供了强大的函数来排序数组和对象,例如 sortasortksortusort。本教程将通过实际例子来介绍这些函数。

使用 sort 进行基本排序

sort 函数按升序对数组进行排序,并重新索引数值键。

basic_sort.php
<?php

declare(strict_types=1);

$numbers = [3, 1, 4, 1, 5];
sort($numbers);
print_r($numbers);

这会将 $numbers 按升序排序。原始数组 [3, 1, 4, 1, 5] 变为 [1, 1, 3, 4, 5]。键被重置为 0 到 4。

使用 sort 排序字符串

使用 sort 按字母顺序排序字符串数组。

sort_strings.php
<?php

declare(strict_types=1);

$fruits = ["banana", "apple", "cherry"];
sort($fruits);
print_r($fruits);

这会将 $fruits 按字母顺序排序。结果是 ["apple", "banana", "cherry"],键从 0 重新索引。

使用 asort 保留键

asort 函数按值排序,保留键关联。

asort_example.php
<?php

declare(strict_types=1);

$scores = ["John" => 85, "Jane" => 92, "Bob" => 78];
asort($scores);
print_r($scores);

这会按值对 $scores 进行排序。结果是 ["Bob" => 78, "John" => 85, "Jane" => 92],键被保留。

使用 ksort 按键排序

ksort 函数按升序键对数组进行排序。

ksort_example.php
<?php

declare(strict_types=1);

$data = ["z" => 1, "x" => 2, "y" => 3];
ksort($data);
print_r($data);

这会按键对 $data 进行排序。结果是 ["x" => 2, "y" => 3, "z" => 1],值与其原始键相关联。

使用 rsort 降序排序

rsort 函数按降序对数组进行排序。

rsort_example.php
<?php

declare(strict_types=1);

$numbers = [3, 1, 4, 1, 5];
rsort($numbers);
print_r($numbers);

这会将 $numbers 按降序排序。结果是 [5, 4, 3, 1, 1],键从 0 重新索引。

使用 usort 进行自定义排序

usort 函数使用自定义比较函数进行排序。

usort_example.php
<?php

declare(strict_types=1);

$numbers = [10, 5, 8, 3];
usort($numbers, fn($a, $b): int => $b - $a);
print_r($numbers);

这会使用箭头函数按降序对 $numbers 进行排序。回调函数返回负值、零或正值以确定顺序。结果是 [10, 8, 5, 3]。

按属性对对象排序

使用 usort 按属性值对对象进行排序。

sort_objects.php
<?php

declare(strict_types=1);

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

$products = [
    new Product("Phone", 500),
    new Product("Laptop", 1000),
    new Product("Tablet", 300)
];

usort($products, fn(Product $a, Product $b): int =>  
    $a->price <=> $b->price);
print_r($products);

这会按价格对 $products 进行排序。太空船运算符 (<=>) 比较价格,导致对象排序为 "Tablet" (300), "Phone" (500), "Laptop" (1000)。

使用 uasort 排序关联数组

uasort 函数使用自定义函数按值排序,保留键。

uasort_example.php
<?php

declare(strict_types=1);

$scores = ["John" => 85, "Jane" => 92, "Bob" => 78];
uasort($scores, fn($a, $b): int => $b <=> $a);
print_r($scores);

这会按降序对 $scores 按值排序。结果是 ["Jane" => 92, "John" => 85, "Bob" => 78],键保持不变。

使用 uksort 按键排序

uksort 函数使用自定义函数按键排序。

uksort_example.php
<?php

declare(strict_types=1);

$data = ["z" => 1, "x" => 2, "y" => 3];
uksort($data, fn(string $a, string $b): int => strlen($a) <=> strlen($b));
print_r($data);

这会按键长度对 $data 进行排序。结果是 ["x" => 2, "y" => 3, "z" => 1],因为所有键都是单字符,默认按字母顺序排序。

排序多维数组

使用 usort 按特定键对多维数组进行排序。

sort_multi.php
<?php

declare(strict_types=1);

$users = [
    ["name" => "John", "age" => 25],
    ["name" => "Jane", "age" => 30],
    ["name" => "Bob", "age" => 20]
];
usort($users, fn(array $a, array $b): int => $a["age"] <=> $b["age"]);
print_r($users);

这会按年龄对 $users 进行排序。结果是 "Bob" (20), "John" (25), "Jane" (30),数组结构被保留。

按多个条件排序

使用 usort 按多个属性对对象进行排序。

sort_multi_criteria.php
<?php

declare(strict_types=1);

class Item {
    public function __construct(
        public string $name,
        public int $stock
    ) {}
}

$items = [
    new Item("Laptop", 5),
    new Item("Phone", 10),
    new Item("Tablet", 5)
];

usort($items, fn(Item $a, Item $b): int => $a->stock <=> 
    $b->stock ?: $a->name <=> $b->name);
print_r($items);

这会按库存量,然后按名称对 $items 进行排序。结果是 "Laptop" (5), "Tablet" (5), "Phone" (10),如果有相同库存量则按字母顺序排序。

使用 array_multisort 排序

使用 array_multisort 排序多个数组或列。

array_multisort_example.php
<?php

declare(strict_types=1);

$names = ["John", "Jane", "Bob"];
$ages = [25, 30, 20];
array_multisort($ages, SORT_ASC, $names);
print_r([$names, $ages]);

这会排序 $ages 并对齐 $names。结果是 $names = ["Bob", "John", "Jane"] 和 $ages = [20, 25, 30]。

按年龄排序用户

按年龄(从出生日期计算)对用户对象数组进行排序。

sort_users_by_age.php
<?php

declare(strict_types=1);

class User {
    public function __construct(
        public string $first_name,
        public string $last_name,
        public string $date_of_birth
    ) {}
}

$users = [
    new User("John", "Doe", "2000-05-15"),
    new User("Jane", "Smith", "1995-08-22"),
    new User("Bob", "Brown", "1998-11-30")
];

usort($users, fn(User $a, User $b): int => 
    (new DateTime($a->date_of_birth)) <=> (new DateTime($b->date_of_birth)));
print_r($users);

这会按出生日期对 $users 进行排序,从最年长的人开始。回调函数比较 $date_of_birth 值,结果是 "Jane" (1995), "Bob" (1998), "John" (2000)。

排序的最佳实践

来源

PHP 排序文档

本教程探讨了使用现代技术和实际例子在 PHP 中对数组和对象进行排序。

作者

我叫 Jan Bodnar,是一位经验丰富的程序员,拥有十多年的经验。自 2007 年以来,我撰写了 1400 多篇文章和 8 本电子书。

列出 所有 PHP 教程