PHP 数组排序函数:全面指南382


在 PHP 中,您可以使用各种函数对数组中的元素进行排序。这些函数允许您根据特定标准组织和排列数组元素,以便于处理和访问。

sort() 函数

sort() 函数对数组中的元素进行升序排序。它根据元素的自然顺序对元素进行排序,对于数字数组,按升序排序,对于字符串数组,按字母顺序排序。```php
$array = [3, 6, 1, 9, 4];
sort($array);
// 结果: [1, 3, 4, 6, 9]
```

rsort() 函数

rsort() 函数对数组中的元素进行降序排序。与 sort() 相反,它将最大的元素放在数组的开头。```php
rsort($array);
// 结果: [9, 6, 4, 3, 1]
```

asort() 函数

asort() 函数对数组中的元素进行升序排序,但它会保持键值关联。这意味着键值将与排序后的元素保持关联。```php
$array = [
'name' => 'John',
'age' => 30,
'city' => 'New York'
];
asort($array);
// 结果:
// [
// 'age' => 30,
// 'city' => 'New York',
// 'name' => 'John'
// ]
```

arsort() 函数

arsort() 函数对数组中的元素进行降序排序,同时保持键值关联。```php
arsort($array);
// 结果:
// [
// 'name' => 'John',
// 'city' => 'New York',
// 'age' => 30
// ]
```

ksort() 函数

ksort() 函数按键对数组中的元素进行升序排序。它重新排列键值,使它们按升序排列,同时保留关联的值。```php
ksort($array);
// 结果:
// [
// 'age' => 30,
// 'city' => 'New York',
// 'name' => 'John'
// ]
```

krsort() 函数

krsort() 函数按键对数组中的元素进行降序排序。与 ksort() 相反,它将最大的键值放在数组的开头。```php
krsort($array);
// 结果:
// [
// 'name' => 'John',
// 'city' => 'New York',
// 'age' => 30
// ]
```

natsort() 函数

natsort() 函数对字符串数组中的元素进行自然排序。它根据字符串的自然顺序对元素进行排序,考虑数字和字母字符。```php
$array = ['123', '1', '10', '2'];
natsort($array);
// 结果: [1, 2, 10, 123]
```

natcasesort() 函数

natcasesort() 函数对字符串数组中的元素进行不区分大小写的自然排序。与 natsort() 相似,但它忽略字符串中的大小写差异。```php
$array = ['123', '1', '10', '2', '100'];
natcasesort($array);
// 结果: [1, 2, 10, 100, 123]
```

shuffles() 函数

shuffles() 函数随机排列数组中的元素。它不会对元素进行排序,而是改变它们的顺序,使它们成为随机排列。```php
$array = [3, 6, 1, 9, 4];
shuffle($array);
// 结果: [1, 4, 9, 6, 3]
```

multisort() 函数

multisort() 函数对多维数组中的元素进行排序。它根据多个键对数组元素进行排序,允许您指定排序顺序(升序或降序)。```php
$array = [
['name' => 'John', 'age' => 30],
['name' => 'Mary', 'age' => 25],
['name' => 'Bob', 'age' => 35]
];
multisort(array_column($array, 'age'), SORT_ASC, $array);
// 结果:
// [
// ['name' => 'Mary', 'age' => 25],
// ['name' => 'John', 'age' => 30],
// ['name' => 'Bob', 'age' => 35]
// ]
```

usort() 函数

usort() 函数使用用户自定义比较函数对数组中的元素进行排序。该比较函数用于比较数组中两个元素,并根据返回的值确定排序顺序。```php
function compare($a, $b) {
return strcmp($a['name'], $b['name']);
}
usort($array, 'compare');
// 结果:
// [
// ['name' => 'Bob', 'age' => 35],
// ['name' => 'John', 'age' => 30],
// ['name' => 'Mary', 'age' => 25]
// ]
```

uksort() 函数

uksort() 函数使用用户自定义比较函数对数组的键进行排序。与 usort() 类似,该比较函数用于比较数组中两个键,并根据返回的值确定排序顺序。```php
function compareKeys($a, $b) {
return strcmp($a, $b);
}
uksort($array, 'compareKeys');
// 结果:
// [
// 'Bob' => ['name' => 'Bob', 'age' => 35],
// 'John' => ['name' => 'John', 'age' => 30],
// 'Mary' => ['name' => 'Mary', 'age' => 25]
// ]
```

2024-10-31


上一篇:如何使用 PHP 下载文件

下一篇:PHP 获取北京时间