PHP 数组排序
核对 PHP 六大内置数组排序函数 sort/rsort/asort/ksort/arsort/krsort 的原地排序行为、键保留差异,以及 PHP 8 稳定排序与比较标志实测。
学完这一章,你能够
- 核对 PHP 六大内置数组排序函数 sort/rsort/asort/ksort/arsort/krsort 的原地排序行为、键保留差异,以及 PHP 8 稳定排序与比较标志实测。
六大数组排序函数分工
PHP 数组排序函数均通过引用直接原地修改原数组并返回布尔值 `true`。按排序维度与方向分为三组六函数:`sort()` / `rsort()` 按值升序或降序排列并重置数字键;`asort()` / `arsort()` 按值升序或降序排列并保留原键名关联;`ksort()` / `krsort()` 按键名升序或降序排列。
值排序与键重置:sort() 与 rsort()
`sort()` 按升序重排数组元素。本站 PHP 8.4.27 实测:字符串数组 `["Volvo", "BMW", "Toyota"]` 排为 `["BMW", "Toyota", "Volvo"]`,数字数组 `[4, 6, 2, 22, 11]` 排为 `[2, 4, 6, 11, 22]`。若对关联数组调用 `sort()`,原有字符串键会被丢弃并重建为 `[0, 1, ...]`。
`rsort()` 按降序重排元素并同样重置索引:实测 `$cars` 排为 `["Volvo", "Toyota", "BMW"]`,`$numbers` 排为 `[22, 11, 6, 4, 2]`。
关联数组排序、稳定性与比较标志
处理关联数组 `["Peter" => "35", "Ben" => "37", "Joe" => "43"]` 时,若需保留键与值的对应关系,应使用 `asort()` 或 `ksort()`。实测将乱序数组 `["Joe" => "43", "Peter" => "35", "Ben" => "37"]` 执行 `asort()` 后,键序恢复为 `["Peter", "Ben", "Joe"]`(值依次 `35, 37, 43`);执行 `ksort()` 按键名字母升序得 `["Ben", "Joe", "Peter"]`(对应值 `37, 43, 35`)。
对应降序版本中,实测 `arsort()` 按值降序得键序 `["Joe", "Ben", "Peter"]`,`krsort()` 按键降序得 `["Peter", "Joe", "Ben"]`。此外自 PHP 8.0 起所有内置排序均为稳定排序(实测值同为 `10` 的 `'first'` 与 `'third'` 排序后仍保持相对先后 `['second', 'first', 'third']`);面对数字字符串时可通过第二参数控制比较模式:实测 `['10', '2', '1']` 用 `SORT_STRING` 排为 `['1', '10', '2']`,用 `SORT_NUMERIC` 排为 `['1', '2', '10']`。更多排序函数可参考 PHP 官方 Array 手册。
运行 PHP 8.4 六大数组排序函数、稳定排序与排序标志实验
<?php
declare(strict_types=1);
$cases = [];
// Case 1: sort() ascending for strings and numbers + key re-indexing
$cars = ['Volvo', 'BMW', 'Toyota'];
$okCars = sort($cars);
$numbers = [4, 6, 2, 22, 11];
$okNums = sort($numbers);
$assocReindex = ['b' => 20, 'a' => 10];
sort($assocReindex);
$c1Actual = [
'cars' => $cars,
'numbers' => $numbers,
'returns_true' => ($okCars && $okNums),
'reindexed_keys' => array_keys($assocReindex),
];
$c1Expected = [
'cars' => ['BMW', 'Toyota', 'Volvo'],
'numbers' => [2, 4, 6, 11, 22],
'returns_true' => true,
'reindexed_keys' => [0, 1],
];
$cases[] = [
'name' => 'sort_ascending_alpha_and_num',
'passed' => $c1Actual === $c1Expected,
'expected' => $c1Expected,
'actual' => $c1Actual,
];
// Case 2: rsort() descending for strings and numbers
$carsDesc = ['Volvo', 'BMW', 'Toyota'];
rsort($carsDesc);
$numsDesc = [4, 6, 2, 22, 11];
rsort($numsDesc);
$c2Actual = [
'cars' => $carsDesc,
'numbers' => $numsDesc,
];
$c2Expected = [
'cars' => ['Volvo', 'Toyota', 'BMW'],
'numbers' => [22, 11, 6, 4, 2],
];
$cases[] = [
'name' => 'rsort_descending_alpha_and_num',
'passed' => $c2Actual === $c2Expected,
'expected' => $c2Expected,
'actual' => $c2Actual,
];
// Case 3: asort() by value ascending & ksort() by key ascending (preserving associations)
$ageByVal = ['Peter' => '35', 'Ben' => '37', 'Joe' => '43'];
asort($ageByVal);
$ageUnsorted = ['Joe' => '43', 'Peter' => '35', 'Ben' => '37'];
asort($ageUnsorted);
$ageByKey = ['Peter' => '35', 'Ben' => '37', 'Joe' => '43'];
ksort($ageByKey);
$c3Actual = [
'asort_keys' => array_keys($ageByVal),
'asort_from_unsorted_keys' => array_keys($ageUnsorted),
'asort_values' => array_values($ageUnsorted),
'ksort_keys' => array_keys($ageByKey),
'ksort_values' => array_values($ageByKey),
];
$c3Expected = [
'asort_keys' => ['Peter', 'Ben', 'Joe'],
'asort_from_unsorted_keys' => ['Peter', 'Ben', 'Joe'],
'asort_values' => ['35', '37', '43'],
'ksort_keys' => ['Ben', 'Joe', 'Peter'],
'ksort_values' => ['37', '43', '35'],
];
$cases[] = [
'name' => 'asort_and_ksort_ascending',
'passed' => $c3Actual === $c3Expected,
'expected' => $c3Expected,
'actual' => $c3Actual,
];
// Case 4: arsort() & krsort() descending + PHP 8 stable sort & SORT_STRING vs SORT_NUMERIC
$ageValDesc = ['Peter' => '35', 'Ben' => '37', 'Joe' => '43'];
arsort($ageValDesc);
$ageKeyDesc = ['Peter' => '35', 'Ben' => '37', 'Joe' => '43'];
krsort($ageKeyDesc);
$stable = ['first' => 10, 'second' => 5, 'third' => 10];
asort($stable);
$strFlag = ['10', '2', '1'];
sort($strFlag, SORT_STRING);
$numFlag = ['10', '2', '1'];
sort($numFlag, SORT_NUMERIC);
$c4Actual = [
'arsort_keys' => array_keys($ageValDesc),
'krsort_keys' => array_keys($ageKeyDesc),
'stable_keys' => array_keys($stable),
'sort_string' => $strFlag,
'sort_numeric' => $numFlag,
];
$c4Expected = [
'arsort_keys' => ['Joe', 'Ben', 'Peter'],
'krsort_keys' => ['Peter', 'Joe', 'Ben'],
'stable_keys' => ['second', 'first', 'third'],
'sort_string' => ['1', '10', '2'],
'sort_numeric' => ['1', '2', '10'],
];
$cases[] = [
'name' => 'arsort_and_krsort_descending',
'passed' => $c4Actual === $c4Expected,
'expected' => $c4Expected,
'actual' => $c4Actual,
];
echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
- 核对 sort/rsort 字母与数字升降序及键重置、asort/ksort/arsort/krsort 键保留结果、PHP 8 稳定排序以及 SORT_STRING 与 SORT_NUMERIC 差异。
所需环境:Windows x64、PHP 8.4 本地 CLI 环境。
当前源码 SHA256:e6d894a20ab5f8ff5c1f707c01def267b047d4e88205ffaa3824c385f9d5a332
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、PHP 8.4 本地 CLI 环境。
ZIP SHA256:f5d8d4556545775defe9966dcea815d83392e3bd6448e42b1574f42c35a31265
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
对关联数组 ['b' => 20, 'a' => 10] 分别调用 sort() 与 asort(),排序后的数组键名有什么不同?
展开参考解答
sort() 会丢弃字符串键 'a'/'b' 并重新分配数字索引 [0 => 10, 1 => 20];asort() 则保留原有键值关联,结果为 ['a' => 10, 'b' => 20]。