PHP的二维数组按指定键名排序
使用 usort() 函数
usort() 函数可通过用户自定义的比较函数对数组进行排序。
// 示例二维数组
$students = [
['name' => 'Alice', 'score' => 85],
['name' => 'Bob', 'score' => 92],
['name' => 'Charlie', 'score' => 78]
];
// 定义排序函数,按 score 键升序排序
usort($students, function ($a, $b) {
return $a['score'] - $b['score'];
});
// 输出排序后的数组
print_r($students);
?>
代码解释
首先定义了一个二维数组 $students,每个元素是一个包含 name 和 score 键的关联数组。
然后使用 usort() 函数对 $students 数组进行排序。usort() 接受一个用户自定义的比较函数,该函数接受两个参数 $a 和 $b,分别代表数组中的两个元素。
在比较函数中,通过 $a['score'] - $b['score'] 来确定元素的顺序。如果结果小于 0,则 $a 排在 $b 前面;如果结果大于 0,则 $a 排在 $b 后面;如果结果等于 0,则它们的相对顺序不变。
若要按降序排序,可将比较函数改为 return $b['score'] - $a['score'];。
使用 array_multisort() 函数
array_multisort() 函数可以对多个数组或多维数组进行排序。
?php
// 示例二维数组
$students = [
['name' => 'Alice', 'score' => 85],
['name' => 'Bob', 'score' => 92],
['name' => 'Charlie', 'score' => 78]
];
// 提取要排序的键值到一个新数组
$scores = array_column($students, 'score');
// 按 score 键升序排序
array_multisort($scores, SORT_ASC, $students);
// 输出排序后的数组
print_r($students);
?>
代码解释
同样先定义了二维数组 $students。
使用 array_column() 函数从 $students 数组中提取 score 键的值,存储到 $scores 数组中。
调用 array_multisort() 函数,第一个参数是 $scores 数组,第二个参数 SORT_ASC 表示升序排序,第三个参数是要排序的原始二维数组 $students。
若要按降序排序,可将第二个参数改为 SORT_DESC。
升级版:
通过在比较函数中依次比较多个键名的值,就能实现按多个键名排序。
// 定义排序函数,先按 score 降序排序,score 相同时按 age 升序排序
usort($students, function ($a, $b) {
// 先比较 score 键的值
if ($a['score'] !== $b['score']) {
return $b['score'] - $a['score'];
}
// score 相同时,比较 age 键的值
return $a['age'] - $b['age'];
});